Allow scalarrepl to treat an all-zero GEP just as bitcast.
[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/Pass.h"
31 #include "llvm/Analysis/Dominators.h"
32 #include "llvm/Target/TargetData.h"
33 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/GetElementPtrTypeIterator.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Compiler.h"
38 #include "llvm/ADT/SmallVector.h"
39 #include "llvm/ADT/Statistic.h"
40 #include "llvm/ADT/StringExtras.h"
41 using namespace llvm;
42
43 STATISTIC(NumReplaced,  "Number of allocas broken up");
44 STATISTIC(NumPromoted,  "Number of allocas promoted");
45 STATISTIC(NumConverted, "Number of aggregates converted to scalar");
46 STATISTIC(NumGlobals,   "Number of allocas copied from constant global");
47
48 namespace {
49   struct VISIBILITY_HIDDEN SROA : public FunctionPass {
50     static char ID; // Pass identification, replacement for typeid
51     explicit SROA(signed T = -1) : FunctionPass(&ID) {
52       if (T == -1)
53         SRThreshold = 128;
54       else
55         SRThreshold = T;
56     }
57
58     bool runOnFunction(Function &F);
59
60     bool performScalarRepl(Function &F);
61     bool performPromotion(Function &F);
62
63     // getAnalysisUsage - This pass does not require any passes, but we know it
64     // will not alter the CFG, so say so.
65     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
66       AU.addRequired<DominatorTree>();
67       AU.addRequired<DominanceFrontier>();
68       AU.addRequired<TargetData>();
69       AU.setPreservesCFG();
70     }
71
72   private:
73     /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
74     /// information about the uses.  All these fields are initialized to false
75     /// and set to true when something is learned.
76     struct AllocaInfo {
77       /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
78       bool isUnsafe : 1;
79       
80       /// needsCanon - This is set to true if there is some use of the alloca
81       /// that requires canonicalization.
82       bool needsCanon : 1;
83       
84       /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
85       bool isMemCpySrc : 1;
86
87       /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
88       bool isMemCpyDst : 1;
89
90       AllocaInfo()
91         : isUnsafe(false), needsCanon(false), 
92           isMemCpySrc(false), isMemCpyDst(false) {}
93     };
94     
95     unsigned SRThreshold;
96
97     void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
98
99     int isSafeAllocaToScalarRepl(AllocationInst *AI);
100
101     void isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
102                                AllocaInfo &Info);
103     void isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
104                          AllocaInfo &Info);
105     void isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
106                                         unsigned OpNo, AllocaInfo &Info);
107     void isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI,
108                                         AllocaInfo &Info);
109     
110     void DoScalarReplacement(AllocationInst *AI, 
111                              std::vector<AllocationInst*> &WorkList);
112     void CanonicalizeAllocaUsers(AllocationInst *AI);
113     AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
114     
115     void RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
116                                     SmallVector<AllocaInst*, 32> &NewElts);
117     
118     const Type *CanConvertToScalar(Value *V, bool &IsNotTrivial);
119     void ConvertToScalar(AllocationInst *AI, const Type *Ty);
120     void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset);
121     Value *ConvertUsesOfLoadToScalar(LoadInst *LI, AllocaInst *NewAI, 
122                                      unsigned Offset);
123     Value *ConvertUsesOfStoreToScalar(StoreInst *SI, AllocaInst *NewAI, 
124                                       unsigned Offset);
125     static Instruction *isOnlyCopiedFromConstantGlobal(AllocationInst *AI);
126   };
127 }
128
129 char SROA::ID = 0;
130 static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
131
132 // Public interface to the ScalarReplAggregates pass
133 FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) { 
134   return new SROA(Threshold);
135 }
136
137
138 bool SROA::runOnFunction(Function &F) {
139   bool Changed = performPromotion(F);
140   while (1) {
141     bool LocalChange = performScalarRepl(F);
142     if (!LocalChange) break;   // No need to repromote if no scalarrepl
143     Changed = true;
144     LocalChange = performPromotion(F);
145     if (!LocalChange) break;   // No need to re-scalarrepl if no promotion
146   }
147
148   return Changed;
149 }
150
151
152 bool SROA::performPromotion(Function &F) {
153   std::vector<AllocaInst*> Allocas;
154   DominatorTree         &DT = getAnalysis<DominatorTree>();
155   DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
156
157   BasicBlock &BB = F.getEntryBlock();  // Get the entry node for the function
158
159   bool Changed = false;
160
161   while (1) {
162     Allocas.clear();
163
164     // Find allocas that are safe to promote, by looking at all instructions in
165     // the entry node
166     for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
167       if (AllocaInst *AI = dyn_cast<AllocaInst>(I))       // Is it an alloca?
168         if (isAllocaPromotable(AI))
169           Allocas.push_back(AI);
170
171     if (Allocas.empty()) break;
172
173     PromoteMemToReg(Allocas, DT, DF);
174     NumPromoted += Allocas.size();
175     Changed = true;
176   }
177
178   return Changed;
179 }
180
181 /// getNumSAElements - Return the number of elements in the specific struct or
182 /// array.
183 static uint64_t getNumSAElements(const Type *T) {
184   if (const StructType *ST = dyn_cast<StructType>(T))
185     return ST->getNumElements();
186   return cast<ArrayType>(T)->getNumElements();
187 }
188
189 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
190 // which runs on all of the malloc/alloca instructions in the function, removing
191 // them if they are only used by getelementptr instructions.
192 //
193 bool SROA::performScalarRepl(Function &F) {
194   std::vector<AllocationInst*> WorkList;
195
196   // Scan the entry basic block, adding any alloca's and mallocs to the worklist
197   BasicBlock &BB = F.getEntryBlock();
198   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
199     if (AllocationInst *A = dyn_cast<AllocationInst>(I))
200       WorkList.push_back(A);
201
202   const TargetData &TD = getAnalysis<TargetData>();
203   
204   // Process the worklist
205   bool Changed = false;
206   while (!WorkList.empty()) {
207     AllocationInst *AI = WorkList.back();
208     WorkList.pop_back();
209     
210     // Handle dead allocas trivially.  These can be formed by SROA'ing arrays
211     // with unused elements.
212     if (AI->use_empty()) {
213       AI->eraseFromParent();
214       continue;
215     }
216     
217     // If we can turn this aggregate value (potentially with casts) into a
218     // simple scalar value that can be mem2reg'd into a register value.
219     bool IsNotTrivial = false;
220     if (const Type *ActualType = CanConvertToScalar(AI, IsNotTrivial))
221       if (IsNotTrivial && ActualType != Type::VoidTy) {
222         ConvertToScalar(AI, ActualType);
223         Changed = true;
224         continue;
225       }
226
227     // Check to see if we can perform the core SROA transformation.  We cannot
228     // transform the allocation instruction if it is an array allocation
229     // (allocations OF arrays are ok though), and an allocation of a scalar
230     // value cannot be decomposed at all.
231     if (!AI->isArrayAllocation() &&
232         (isa<StructType>(AI->getAllocatedType()) ||
233          isa<ArrayType>(AI->getAllocatedType())) &&
234         AI->getAllocatedType()->isSized() &&
235         // Do not promote any struct whose size is larger than "128" bytes.
236         TD.getABITypeSize(AI->getAllocatedType()) < SRThreshold &&
237         // Do not promote any struct into more than "32" separate vars.
238         getNumSAElements(AI->getAllocatedType()) < SRThreshold/4) {
239       // Check that all of the users of the allocation are capable of being
240       // transformed.
241       switch (isSafeAllocaToScalarRepl(AI)) {
242       default: assert(0 && "Unexpected value!");
243       case 0:  // Not safe to scalar replace.
244         break;
245       case 1:  // Safe, but requires cleanup/canonicalizations first
246         CanonicalizeAllocaUsers(AI);
247         // FALL THROUGH.
248       case 3:  // Safe to scalar replace.
249         DoScalarReplacement(AI, WorkList);
250         Changed = true;
251         continue;
252       }
253     }
254     
255     // Check to see if this allocation is only modified by a memcpy/memmove from
256     // a constant global.  If this is the case, we can change all users to use
257     // the constant global instead.  This is commonly produced by the CFE by
258     // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
259     // is only subsequently read.
260     if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
261       DOUT << "Found alloca equal to global: " << *AI;
262       DOUT << "  memcpy = " << *TheCopy;
263       Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
264       AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
265       TheCopy->eraseFromParent();  // Don't mutate the global.
266       AI->eraseFromParent();
267       ++NumGlobals;
268       Changed = true;
269       continue;
270     }
271         
272     // Otherwise, couldn't process this.
273   }
274
275   return Changed;
276 }
277
278 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
279 /// predicate, do SROA now.
280 void SROA::DoScalarReplacement(AllocationInst *AI, 
281                                std::vector<AllocationInst*> &WorkList) {
282   DOUT << "Found inst to SROA: " << *AI;
283   SmallVector<AllocaInst*, 32> ElementAllocas;
284   if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
285     ElementAllocas.reserve(ST->getNumContainedTypes());
286     for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
287       AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0, 
288                                       AI->getAlignment(),
289                                       AI->getName() + "." + utostr(i), AI);
290       ElementAllocas.push_back(NA);
291       WorkList.push_back(NA);  // Add to worklist for recursive processing
292     }
293   } else {
294     const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
295     ElementAllocas.reserve(AT->getNumElements());
296     const Type *ElTy = AT->getElementType();
297     for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
298       AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
299                                       AI->getName() + "." + utostr(i), AI);
300       ElementAllocas.push_back(NA);
301       WorkList.push_back(NA);  // Add to worklist for recursive processing
302     }
303   }
304
305   // Now that we have created the alloca instructions that we want to use,
306   // expand the getelementptr instructions to use them.
307   //
308   while (!AI->use_empty()) {
309     Instruction *User = cast<Instruction>(AI->use_back());
310     if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
311       RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
312       BCInst->eraseFromParent();
313       continue;
314     }
315     
316     // Replace:
317     //   %res = load { i32, i32 }* %alloc
318     // with:
319     //   %load.0 = load i32* %alloc.0
320     //   %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0 
321     //   %load.1 = load i32* %alloc.1
322     //   %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1 
323     // (Also works for arrays instead of structs)
324     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
325       Value *Insert = UndefValue::get(LI->getType());
326       for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
327         Value *Load = new LoadInst(ElementAllocas[i], "load", LI);
328         Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
329       }
330       LI->replaceAllUsesWith(Insert);
331       LI->eraseFromParent();
332       continue;
333     }
334
335     // Replace:
336     //   store { i32, i32 } %val, { i32, i32 }* %alloc
337     // with:
338     //   %val.0 = extractvalue { i32, i32 } %val, 0 
339     //   store i32 %val.0, i32* %alloc.0
340     //   %val.1 = extractvalue { i32, i32 } %val, 1 
341     //   store i32 %val.1, i32* %alloc.1
342     // (Also works for arrays instead of structs)
343     if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
344       Value *Val = SI->getOperand(0);
345       for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
346         Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
347         new StoreInst(Extract, ElementAllocas[i], SI);
348       }
349       SI->eraseFromParent();
350       continue;
351     }
352     
353     GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
354     // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
355     unsigned Idx =
356        (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
357
358     assert(Idx < ElementAllocas.size() && "Index out of range?");
359     AllocaInst *AllocaToUse = ElementAllocas[Idx];
360
361     Value *RepValue;
362     if (GEPI->getNumOperands() == 3) {
363       // Do not insert a new getelementptr instruction with zero indices, only
364       // to have it optimized out later.
365       RepValue = AllocaToUse;
366     } else {
367       // We are indexing deeply into the structure, so we still need a
368       // getelement ptr instruction to finish the indexing.  This may be
369       // expanded itself once the worklist is rerun.
370       //
371       SmallVector<Value*, 8> NewArgs;
372       NewArgs.push_back(Constant::getNullValue(Type::Int32Ty));
373       NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
374       RepValue = GetElementPtrInst::Create(AllocaToUse, NewArgs.begin(),
375                                            NewArgs.end(), "", GEPI);
376       RepValue->takeName(GEPI);
377     }
378     
379     // If this GEP is to the start of the aggregate, check for memcpys.
380     if (Idx == 0) {
381       bool IsStartOfAggregateGEP = true;
382       for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i) {
383         if (!isa<ConstantInt>(GEPI->getOperand(i))) {
384           IsStartOfAggregateGEP = false;
385           break;
386         }
387         if (!cast<ConstantInt>(GEPI->getOperand(i))->isZero()) {
388           IsStartOfAggregateGEP = false;
389           break;
390         }
391       }
392       
393       if (IsStartOfAggregateGEP)
394         RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas);
395     }
396     
397
398     // Move all of the users over to the new GEP.
399     GEPI->replaceAllUsesWith(RepValue);
400     // Delete the old GEP
401     GEPI->eraseFromParent();
402   }
403
404   // Finally, delete the Alloca instruction
405   AI->eraseFromParent();
406   NumReplaced++;
407 }
408
409
410 /// isSafeElementUse - Check to see if this use is an allowed use for a
411 /// getelementptr instruction of an array aggregate allocation.  isFirstElt
412 /// indicates whether Ptr is known to the start of the aggregate.
413 ///
414 void SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
415                             AllocaInfo &Info) {
416   for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
417        I != E; ++I) {
418     Instruction *User = cast<Instruction>(*I);
419     switch (User->getOpcode()) {
420     case Instruction::Load:  break;
421     case Instruction::Store:
422       // Store is ok if storing INTO the pointer, not storing the pointer
423       if (User->getOperand(0) == Ptr) return MarkUnsafe(Info);
424       break;
425     case Instruction::GetElementPtr: {
426       GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
427       bool AreAllZeroIndices = isFirstElt;
428       if (GEP->getNumOperands() > 1) {
429         if (!isa<ConstantInt>(GEP->getOperand(1)) ||
430             !cast<ConstantInt>(GEP->getOperand(1))->isZero())
431           // Using pointer arithmetic to navigate the array.
432           return MarkUnsafe(Info);
433        
434         if (AreAllZeroIndices) {
435           for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) {
436             if (!isa<ConstantInt>(GEP->getOperand(i)) ||    
437                 !cast<ConstantInt>(GEP->getOperand(i))->isZero()) {
438               AreAllZeroIndices = false;
439               break;
440             }
441           }
442         }
443       }
444       isSafeElementUse(GEP, AreAllZeroIndices, AI, Info);
445       if (Info.isUnsafe) return;
446       break;
447     }
448     case Instruction::BitCast:
449       if (isFirstElt) {
450         isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI, Info);
451         if (Info.isUnsafe) return;
452         break;
453       }
454       DOUT << "  Transformation preventing inst: " << *User;
455       return MarkUnsafe(Info);
456     case Instruction::Call:
457       if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
458         if (isFirstElt) {
459           isSafeMemIntrinsicOnAllocation(MI, AI, I.getOperandNo(), Info);
460           if (Info.isUnsafe) return;
461           break;
462         }
463       }
464       DOUT << "  Transformation preventing inst: " << *User;
465       return MarkUnsafe(Info);
466     default:
467       DOUT << "  Transformation preventing inst: " << *User;
468       return MarkUnsafe(Info);
469     }
470   }
471   return;  // All users look ok :)
472 }
473
474 /// AllUsersAreLoads - Return true if all users of this value are loads.
475 static bool AllUsersAreLoads(Value *Ptr) {
476   for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
477        I != E; ++I)
478     if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
479       return false;
480   return true;
481 }
482
483 /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
484 /// aggregate allocation.
485 ///
486 void SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
487                                  AllocaInfo &Info) {
488   if (BitCastInst *C = dyn_cast<BitCastInst>(User))
489     return isSafeUseOfBitCastedAllocation(C, AI, Info);
490
491   if (isa<LoadInst>(User))
492     return; // Loads (returning a first class aggregrate) are always rewritable
493
494   if (isa<StoreInst>(User) && User->getOperand(0) != AI)
495     return; // Store is ok if storing INTO the pointer, not storing the pointer
496  
497   GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User);
498   if (GEPI == 0)
499     return MarkUnsafe(Info);
500
501   gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
502
503   // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
504   if (I == E ||
505       I.getOperand() != Constant::getNullValue(I.getOperand()->getType())) {
506     return MarkUnsafe(Info);
507   }
508
509   ++I;
510   if (I == E) return MarkUnsafe(Info);  // ran out of GEP indices??
511
512   bool IsAllZeroIndices = true;
513   
514   // If the first index is a non-constant index into an array, see if we can
515   // handle it as a special case.
516   if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
517     if (!isa<ConstantInt>(I.getOperand())) {
518       IsAllZeroIndices = 0;
519       uint64_t NumElements = AT->getNumElements();
520       
521       // If this is an array index and the index is not constant, we cannot
522       // promote... that is unless the array has exactly one or two elements in
523       // it, in which case we CAN promote it, but we have to canonicalize this
524       // out if this is the only problem.
525       if ((NumElements == 1 || NumElements == 2) &&
526           AllUsersAreLoads(GEPI)) {
527         Info.needsCanon = true;
528         return;  // Canonicalization required!
529       }
530       return MarkUnsafe(Info);
531     }
532   }
533  
534   bool hasVector = false;
535   
536   // Walk through the GEP type indices, checking the types that this indexes
537   // into.
538   for (; I != E; ++I) {
539     // Ignore struct elements, no extra checking needed for these.
540     if (isa<StructType>(*I))
541       continue;
542     
543     ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
544     if (!IdxVal) return MarkUnsafe(Info);
545
546     // Are all indices still zero?
547     IsAllZeroIndices &= IdxVal->isZero();
548     
549     if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
550       // This GEP indexes an array.  Verify that this is an in-range constant
551       // integer. Specifically, consider A[0][i]. We cannot know that the user
552       // isn't doing invalid things like allowing i to index an out-of-range
553       // subscript that accesses A[1].  Because of this, we have to reject SROA
554       // of any accesses into structs where any of the components are variables.
555       if (IdxVal->getZExtValue() >= AT->getNumElements())
556         return MarkUnsafe(Info);
557     }
558   
559     // Note if we've seen a vector type yet
560     hasVector |= isa<VectorType>(*I);
561     
562     // Don't SROA pointers into vectors, unless all indices are zero. When all
563     // indices are zero, we only consider this GEP as a bitcast, but will still
564     // not consider breaking up the vector.
565     if (hasVector && !IsAllZeroIndices)
566       return MarkUnsafe(Info);
567   }
568   
569   // If there are any non-simple uses of this getelementptr, make sure to reject
570   // them.
571   return isSafeElementUse(GEPI, IsAllZeroIndices, AI, Info);
572 }
573
574 /// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
575 /// intrinsic can be promoted by SROA.  At this point, we know that the operand
576 /// of the memintrinsic is a pointer to the beginning of the allocation.
577 void SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
578                                           unsigned OpNo, AllocaInfo &Info) {
579   // If not constant length, give up.
580   ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
581   if (!Length) return MarkUnsafe(Info);
582   
583   // If not the whole aggregate, give up.
584   const TargetData &TD = getAnalysis<TargetData>();
585   if (Length->getZExtValue() !=
586       TD.getABITypeSize(AI->getType()->getElementType()))
587     return MarkUnsafe(Info);
588   
589   // We only know about memcpy/memset/memmove.
590   if (!isa<MemCpyInst>(MI) && !isa<MemSetInst>(MI) && !isa<MemMoveInst>(MI))
591     return MarkUnsafe(Info);
592   
593   // Otherwise, we can transform it.  Determine whether this is a memcpy/set
594   // into or out of the aggregate.
595   if (OpNo == 1)
596     Info.isMemCpyDst = true;
597   else {
598     assert(OpNo == 2);
599     Info.isMemCpySrc = true;
600   }
601 }
602
603 /// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
604 /// are 
605 void SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI,
606                                           AllocaInfo &Info) {
607   for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
608        UI != E; ++UI) {
609     if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
610       isSafeUseOfBitCastedAllocation(BCU, AI, Info);
611     } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
612       isSafeMemIntrinsicOnAllocation(MI, AI, UI.getOperandNo(), Info);
613     } else {
614       return MarkUnsafe(Info);
615     }
616     if (Info.isUnsafe) return;
617   }
618 }
619
620 /// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
621 /// to its first element.  Transform users of the cast to use the new values
622 /// instead.
623 void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
624                                       SmallVector<AllocaInst*, 32> &NewElts) {
625   Constant *Zero = Constant::getNullValue(Type::Int32Ty);
626   const TargetData &TD = getAnalysis<TargetData>();
627   
628   Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
629   while (UI != UE) {
630     if (BitCastInst *BCU = dyn_cast<BitCastInst>(*UI)) {
631       RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
632       ++UI;
633       BCU->eraseFromParent();
634       continue;
635     }
636
637     // Otherwise, must be memcpy/memmove/memset of the entire aggregate.  Split
638     // into one per element.
639     MemIntrinsic *MI = dyn_cast<MemIntrinsic>(*UI);
640     
641     // If it's not a mem intrinsic, it must be some other user of a gep of the
642     // first pointer.  Just leave these alone.
643     if (!MI) {
644       ++UI;
645       continue;
646     }
647     
648     // If this is a memcpy/memmove, construct the other pointer as the
649     // appropriate type.
650     Value *OtherPtr = 0;
651     if (MemCpyInst *MCI = dyn_cast<MemCpyInst>(MI)) {
652       if (BCInst == MCI->getRawDest())
653         OtherPtr = MCI->getRawSource();
654       else {
655         assert(BCInst == MCI->getRawSource());
656         OtherPtr = MCI->getRawDest();
657       }
658     } else if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
659       if (BCInst == MMI->getRawDest())
660         OtherPtr = MMI->getRawSource();
661       else {
662         assert(BCInst == MMI->getRawSource());
663         OtherPtr = MMI->getRawDest();
664       }
665     }
666     
667     // If there is an other pointer, we want to convert it to the same pointer
668     // type as AI has, so we can GEP through it.
669     if (OtherPtr) {
670       // It is likely that OtherPtr is a bitcast, if so, remove it.
671       if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
672         OtherPtr = BC->getOperand(0);
673       // All zero GEPs are effectively casts
674       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr))
675         if (GEP->hasAllZeroIndices())
676           OtherPtr = GEP->getOperand(0);
677         
678       if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
679         if (BCE->getOpcode() == Instruction::BitCast)
680           OtherPtr = BCE->getOperand(0);
681       
682       // If the pointer is not the right type, insert a bitcast to the right
683       // type.
684       if (OtherPtr->getType() != AI->getType())
685         OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
686                                    MI);
687     }
688
689     // Process each element of the aggregate.
690     Value *TheFn = MI->getOperand(0);
691     const Type *BytePtrTy = MI->getRawDest()->getType();
692     bool SROADest = MI->getRawDest() == BCInst;
693
694     for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
695       // If this is a memcpy/memmove, emit a GEP of the other element address.
696       Value *OtherElt = 0;
697       if (OtherPtr) {
698         Value *Idx[2] = { Zero, ConstantInt::get(Type::Int32Ty, i) };
699         OtherElt = GetElementPtrInst::Create(OtherPtr, Idx, Idx + 2,
700                                            OtherPtr->getNameStr()+"."+utostr(i),
701                                              MI);
702       }
703
704       Value *EltPtr = NewElts[i];
705       const Type *EltTy =cast<PointerType>(EltPtr->getType())->getElementType();
706       
707       // If we got down to a scalar, insert a load or store as appropriate.
708       if (EltTy->isSingleValueType()) {
709         if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
710           Value *Elt = new LoadInst(SROADest ? OtherElt : EltPtr, "tmp",
711                                     MI);
712           new StoreInst(Elt, SROADest ? EltPtr : OtherElt, MI);
713           continue;
714         } else {
715           assert(isa<MemSetInst>(MI));
716
717           // If the stored element is zero (common case), just store a null
718           // constant.
719           Constant *StoreVal;
720           if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
721             if (CI->isZero()) {
722               StoreVal = Constant::getNullValue(EltTy);  // 0.0, null, 0, <0,0>
723             } else {
724               // If EltTy is a vector type, get the element type.
725               const Type *ValTy = EltTy;
726               if (const VectorType *VTy = dyn_cast<VectorType>(ValTy))
727                 ValTy = VTy->getElementType();
728
729               // Construct an integer with the right value.
730               unsigned EltSize = TD.getTypeSizeInBits(ValTy);
731               APInt OneVal(EltSize, CI->getZExtValue());
732               APInt TotalVal(OneVal);
733               // Set each byte.
734               for (unsigned i = 0; 8*i < EltSize; ++i) {
735                 TotalVal = TotalVal.shl(8);
736                 TotalVal |= OneVal;
737               }
738
739               // Convert the integer value to the appropriate type.
740               StoreVal = ConstantInt::get(TotalVal);
741               if (isa<PointerType>(ValTy))
742                 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
743               else if (ValTy->isFloatingPoint())
744                 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
745               assert(StoreVal->getType() == ValTy && "Type mismatch!");
746               
747               // If the requested value was a vector constant, create it.
748               if (EltTy != ValTy) {
749                 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
750                 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
751                 StoreVal = ConstantVector::get(&Elts[0], NumElts);
752               }
753             }
754             new StoreInst(StoreVal, EltPtr, MI);
755             continue;
756           }
757           // Otherwise, if we're storing a byte variable, use a memset call for
758           // this element.
759         }
760       }
761       
762       // Cast the element pointer to BytePtrTy.
763       if (EltPtr->getType() != BytePtrTy)
764         EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
765     
766       // Cast the other pointer (if we have one) to BytePtrTy. 
767       if (OtherElt && OtherElt->getType() != BytePtrTy)
768         OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
769                                    MI);
770     
771       unsigned EltSize = TD.getABITypeSize(EltTy);
772
773       // Finally, insert the meminst for this element.
774       if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
775         Value *Ops[] = {
776           SROADest ? EltPtr : OtherElt,  // Dest ptr
777           SROADest ? OtherElt : EltPtr,  // Src ptr
778           ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
779           Zero  // Align
780         };
781         CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
782       } else {
783         assert(isa<MemSetInst>(MI));
784         Value *Ops[] = {
785           EltPtr, MI->getOperand(2),  // Dest, Value,
786           ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
787           Zero  // Align
788         };
789         CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
790       }
791     }
792
793     // Finally, MI is now dead, as we've modified its actions to occur on all of
794     // the elements of the aggregate.
795     ++UI;
796     MI->eraseFromParent();
797   }
798 }
799
800 /// HasPadding - Return true if the specified type has any structure or
801 /// alignment padding, false otherwise.
802 static bool HasPadding(const Type *Ty, const TargetData &TD) {
803   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
804     const StructLayout *SL = TD.getStructLayout(STy);
805     unsigned PrevFieldBitOffset = 0;
806     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
807       unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
808
809       // Padding in sub-elements?
810       if (HasPadding(STy->getElementType(i), TD))
811         return true;
812
813       // Check to see if there is any padding between this element and the
814       // previous one.
815       if (i) {
816         unsigned PrevFieldEnd =
817         PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
818         if (PrevFieldEnd < FieldBitOffset)
819           return true;
820       }
821
822       PrevFieldBitOffset = FieldBitOffset;
823     }
824
825     //  Check for tail padding.
826     if (unsigned EltCount = STy->getNumElements()) {
827       unsigned PrevFieldEnd = PrevFieldBitOffset +
828                    TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
829       if (PrevFieldEnd < SL->getSizeInBits())
830         return true;
831     }
832
833   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
834     return HasPadding(ATy->getElementType(), TD);
835   } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
836     return HasPadding(VTy->getElementType(), TD);
837   }
838   return TD.getTypeSizeInBits(Ty) != TD.getABITypeSizeInBits(Ty);
839 }
840
841 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
842 /// an aggregate can be broken down into elements.  Return 0 if not, 3 if safe,
843 /// or 1 if safe after canonicalization has been performed.
844 ///
845 int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
846   // Loop over the use list of the alloca.  We can only transform it if all of
847   // the users are safe to transform.
848   AllocaInfo Info;
849   
850   for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
851        I != E; ++I) {
852     isSafeUseOfAllocation(cast<Instruction>(*I), AI, Info);
853     if (Info.isUnsafe) {
854       DOUT << "Cannot transform: " << *AI << "  due to user: " << **I;
855       return 0;
856     }
857   }
858   
859   // Okay, we know all the users are promotable.  If the aggregate is a memcpy
860   // source and destination, we have to be careful.  In particular, the memcpy
861   // could be moving around elements that live in structure padding of the LLVM
862   // types, but may actually be used.  In these cases, we refuse to promote the
863   // struct.
864   if (Info.isMemCpySrc && Info.isMemCpyDst &&
865       HasPadding(AI->getType()->getElementType(), getAnalysis<TargetData>()))
866     return 0;
867
868   // If we require cleanup, return 1, otherwise return 3.
869   return Info.needsCanon ? 1 : 3;
870 }
871
872 /// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified
873 /// allocation, but only if cleaned up, perform the cleanups required.
874 void SROA::CanonicalizeAllocaUsers(AllocationInst *AI) {
875   // At this point, we know that the end result will be SROA'd and promoted, so
876   // we can insert ugly code if required so long as sroa+mem2reg will clean it
877   // up.
878   for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
879        UI != E; ) {
880     GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI++);
881     if (!GEPI) continue;
882     gep_type_iterator I = gep_type_begin(GEPI);
883     ++I;
884
885     if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
886       uint64_t NumElements = AT->getNumElements();
887
888       if (!isa<ConstantInt>(I.getOperand())) {
889         if (NumElements == 1) {
890           GEPI->setOperand(2, Constant::getNullValue(Type::Int32Ty));
891         } else {
892           assert(NumElements == 2 && "Unhandled case!");
893           // All users of the GEP must be loads.  At each use of the GEP, insert
894           // two loads of the appropriate indexed GEP and select between them.
895           Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(), 
896                               Constant::getNullValue(I.getOperand()->getType()),
897              "isone", GEPI);
898           // Insert the new GEP instructions, which are properly indexed.
899           SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
900           Indices[1] = Constant::getNullValue(Type::Int32Ty);
901           Value *ZeroIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
902                                                      Indices.begin(),
903                                                      Indices.end(),
904                                                      GEPI->getName()+".0", GEPI);
905           Indices[1] = ConstantInt::get(Type::Int32Ty, 1);
906           Value *OneIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
907                                                     Indices.begin(),
908                                                     Indices.end(),
909                                                     GEPI->getName()+".1", GEPI);
910           // Replace all loads of the variable index GEP with loads from both
911           // indexes and a select.
912           while (!GEPI->use_empty()) {
913             LoadInst *LI = cast<LoadInst>(GEPI->use_back());
914             Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
915             Value *One  = new LoadInst(OneIdx , LI->getName()+".1", LI);
916             Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI);
917             LI->replaceAllUsesWith(R);
918             LI->eraseFromParent();
919           }
920           GEPI->eraseFromParent();
921         }
922       }
923     }
924   }
925 }
926
927 /// MergeInType - Add the 'In' type to the accumulated type so far.  If the
928 /// types are incompatible, return true, otherwise update Accum and return
929 /// false.
930 ///
931 /// There are three cases we handle here:
932 ///   1) An effectively-integer union, where the pieces are stored into as
933 ///      smaller integers (common with byte swap and other idioms).
934 ///   2) A union of vector types of the same size and potentially its elements.
935 ///      Here we turn element accesses into insert/extract element operations.
936 ///   3) A union of scalar types, such as int/float or int/pointer.  Here we
937 ///      merge together into integers, allowing the xform to work with #1 as
938 ///      well.
939 static bool MergeInType(const Type *In, const Type *&Accum,
940                         const TargetData &TD) {
941   // If this is our first type, just use it.
942   const VectorType *PTy;
943   if (Accum == Type::VoidTy || In == Accum) {
944     Accum = In;
945   } else if (In == Type::VoidTy) {
946     // Noop.
947   } else if (In->isInteger() && Accum->isInteger()) {   // integer union.
948     // Otherwise pick whichever type is larger.
949     if (cast<IntegerType>(In)->getBitWidth() > 
950         cast<IntegerType>(Accum)->getBitWidth())
951       Accum = In;
952   } else if (isa<PointerType>(In) && isa<PointerType>(Accum)) {
953     // Pointer unions just stay as one of the pointers.
954   } else if (isa<VectorType>(In) || isa<VectorType>(Accum)) {
955     if ((PTy = dyn_cast<VectorType>(Accum)) && 
956         PTy->getElementType() == In) {
957       // Accum is a vector, and we are accessing an element: ok.
958     } else if ((PTy = dyn_cast<VectorType>(In)) && 
959                PTy->getElementType() == Accum) {
960       // In is a vector, and accum is an element: ok, remember In.
961       Accum = In;
962     } else if ((PTy = dyn_cast<VectorType>(In)) && isa<VectorType>(Accum) &&
963                PTy->getBitWidth() == cast<VectorType>(Accum)->getBitWidth()) {
964       // Two vectors of the same size: keep Accum.
965     } else {
966       // Cannot insert an short into a <4 x int> or handle
967       // <2 x int> -> <4 x int>
968       return true;
969     }
970   } else {
971     // Pointer/FP/Integer unions merge together as integers.
972     switch (Accum->getTypeID()) {
973     case Type::PointerTyID: Accum = TD.getIntPtrType(); break;
974     case Type::FloatTyID:   Accum = Type::Int32Ty; break;
975     case Type::DoubleTyID:  Accum = Type::Int64Ty; break;
976     case Type::X86_FP80TyID:  return true;
977     case Type::FP128TyID: return true;
978     case Type::PPC_FP128TyID: return true;
979     default:
980       assert(Accum->isInteger() && "Unknown FP type!");
981       break;
982     }
983     
984     switch (In->getTypeID()) {
985     case Type::PointerTyID: In = TD.getIntPtrType(); break;
986     case Type::FloatTyID:   In = Type::Int32Ty; break;
987     case Type::DoubleTyID:  In = Type::Int64Ty; break;
988     case Type::X86_FP80TyID:  return true;
989     case Type::FP128TyID: return true;
990     case Type::PPC_FP128TyID: return true;
991     default:
992       assert(In->isInteger() && "Unknown FP type!");
993       break;
994     }
995     return MergeInType(In, Accum, TD);
996   }
997   return false;
998 }
999
1000 /// getUIntAtLeastAsBigAs - Return an unsigned integer type that is at least
1001 /// as big as the specified type.  If there is no suitable type, this returns
1002 /// null.
1003 const Type *getUIntAtLeastAsBigAs(unsigned NumBits) {
1004   if (NumBits > 64) return 0;
1005   if (NumBits > 32) return Type::Int64Ty;
1006   if (NumBits > 16) return Type::Int32Ty;
1007   if (NumBits > 8) return Type::Int16Ty;
1008   return Type::Int8Ty;    
1009 }
1010
1011 /// CanConvertToScalar - V is a pointer.  If we can convert the pointee to a
1012 /// single scalar integer type, return that type.  Further, if the use is not
1013 /// a completely trivial use that mem2reg could promote, set IsNotTrivial.  If
1014 /// there are no uses of this pointer, return Type::VoidTy to differentiate from
1015 /// failure.
1016 ///
1017 const Type *SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial) {
1018   const Type *UsedType = Type::VoidTy; // No uses, no forced type.
1019   const TargetData &TD = getAnalysis<TargetData>();
1020   const PointerType *PTy = cast<PointerType>(V->getType());
1021
1022   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1023     Instruction *User = cast<Instruction>(*UI);
1024     
1025     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1026       // FIXME: Loads of a first class aggregrate value could be converted to a
1027       // series of loads and insertvalues
1028       if (!LI->getType()->isSingleValueType())
1029         return 0;
1030
1031       if (MergeInType(LI->getType(), UsedType, TD))
1032         return 0;
1033       
1034     } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1035       // Storing the pointer, not into the value?
1036       if (SI->getOperand(0) == V) return 0;
1037
1038       // FIXME: Stores of a first class aggregrate value could be converted to a
1039       // series of extractvalues and stores
1040       if (!SI->getOperand(0)->getType()->isSingleValueType())
1041         return 0;
1042       
1043       // NOTE: We could handle storing of FP imms into integers here!
1044       
1045       if (MergeInType(SI->getOperand(0)->getType(), UsedType, TD))
1046         return 0;
1047     } else if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
1048       IsNotTrivial = true;
1049       const Type *SubTy = CanConvertToScalar(CI, IsNotTrivial);
1050       if (!SubTy || MergeInType(SubTy, UsedType, TD)) return 0;
1051     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1052       // Check to see if this is stepping over an element: GEP Ptr, int C
1053       if (GEP->getNumOperands() == 2 && isa<ConstantInt>(GEP->getOperand(1))) {
1054         unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
1055         unsigned ElSize = TD.getABITypeSize(PTy->getElementType());
1056         unsigned BitOffset = Idx*ElSize*8;
1057         if (BitOffset > 64 || !isPowerOf2_32(ElSize)) return 0;
1058         
1059         IsNotTrivial = true;
1060         const Type *SubElt = CanConvertToScalar(GEP, IsNotTrivial);
1061         if (SubElt == 0) return 0;
1062         if (SubElt != Type::VoidTy && SubElt->isInteger()) {
1063           const Type *NewTy = 
1064             getUIntAtLeastAsBigAs(TD.getABITypeSizeInBits(SubElt)+BitOffset);
1065           if (NewTy == 0 || MergeInType(NewTy, UsedType, TD)) return 0;
1066           continue;
1067         }
1068       } else if (GEP->getNumOperands() == 3 && 
1069                  isa<ConstantInt>(GEP->getOperand(1)) &&
1070                  isa<ConstantInt>(GEP->getOperand(2)) &&
1071                  cast<ConstantInt>(GEP->getOperand(1))->isZero()) {
1072         // We are stepping into an element, e.g. a structure or an array:
1073         // GEP Ptr, int 0, uint C
1074         const Type *AggTy = PTy->getElementType();
1075         unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
1076         
1077         if (const ArrayType *ATy = dyn_cast<ArrayType>(AggTy)) {
1078           if (Idx >= ATy->getNumElements()) return 0;  // Out of range.
1079         } else if (const VectorType *VectorTy = dyn_cast<VectorType>(AggTy)) {
1080           // Getting an element of the vector.
1081           if (Idx >= VectorTy->getNumElements()) return 0;  // Out of range.
1082
1083           // Merge in the vector type.
1084           if (MergeInType(VectorTy, UsedType, TD)) return 0;
1085           
1086           const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
1087           if (SubTy == 0) return 0;
1088           
1089           if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
1090             return 0;
1091
1092           // We'll need to change this to an insert/extract element operation.
1093           IsNotTrivial = true;
1094           continue;    // Everything looks ok
1095           
1096         } else if (isa<StructType>(AggTy)) {
1097           // Structs are always ok.
1098         } else {
1099           return 0;
1100         }
1101         const Type *NTy = getUIntAtLeastAsBigAs(TD.getABITypeSizeInBits(AggTy));
1102         if (NTy == 0 || MergeInType(NTy, UsedType, TD)) return 0;
1103         const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
1104         if (SubTy == 0) return 0;
1105         if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
1106           return 0;
1107         continue;    // Everything looks ok
1108       }
1109       return 0;
1110     } else {
1111       // Cannot handle this!
1112       return 0;
1113     }
1114   }
1115   
1116   return UsedType;
1117 }
1118
1119 /// ConvertToScalar - The specified alloca passes the CanConvertToScalar
1120 /// predicate and is non-trivial.  Convert it to something that can be trivially
1121 /// promoted into a register by mem2reg.
1122 void SROA::ConvertToScalar(AllocationInst *AI, const Type *ActualTy) {
1123   DOUT << "CONVERT TO SCALAR: " << *AI << "  TYPE = "
1124        << *ActualTy << "\n";
1125   ++NumConverted;
1126   
1127   BasicBlock *EntryBlock = AI->getParent();
1128   assert(EntryBlock == &EntryBlock->getParent()->getEntryBlock() &&
1129          "Not in the entry block!");
1130   EntryBlock->getInstList().remove(AI);  // Take the alloca out of the program.
1131   
1132   // Create and insert the alloca.
1133   AllocaInst *NewAI = new AllocaInst(ActualTy, 0, AI->getName(),
1134                                      EntryBlock->begin());
1135   ConvertUsesToScalar(AI, NewAI, 0);
1136   delete AI;
1137 }
1138
1139
1140 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
1141 /// directly.  This happens when we are converting an "integer union" to a
1142 /// single integer scalar, or when we are converting a "vector union" to a
1143 /// vector with insert/extractelement instructions.
1144 ///
1145 /// Offset is an offset from the original alloca, in bits that need to be
1146 /// shifted to the right.  By the end of this, there should be no uses of Ptr.
1147 void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset) {
1148   while (!Ptr->use_empty()) {
1149     Instruction *User = cast<Instruction>(Ptr->use_back());
1150     
1151     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1152       Value *NV = ConvertUsesOfLoadToScalar(LI, NewAI, Offset);
1153       LI->replaceAllUsesWith(NV);
1154       LI->eraseFromParent();
1155     } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1156       assert(SI->getOperand(0) != Ptr && "Consistency error!");
1157
1158       Value *SV = ConvertUsesOfStoreToScalar(SI, NewAI, Offset);
1159       new StoreInst(SV, NewAI, SI);
1160       SI->eraseFromParent();
1161       
1162     } else if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
1163       ConvertUsesToScalar(CI, NewAI, Offset);
1164       CI->eraseFromParent();
1165     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1166       const PointerType *AggPtrTy = 
1167         cast<PointerType>(GEP->getOperand(0)->getType());
1168       const TargetData &TD = getAnalysis<TargetData>();
1169       unsigned AggSizeInBits =
1170         TD.getABITypeSizeInBits(AggPtrTy->getElementType());
1171
1172       // Check to see if this is stepping over an element: GEP Ptr, int C
1173       unsigned NewOffset = Offset;
1174       if (GEP->getNumOperands() == 2) {
1175         unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
1176         unsigned BitOffset = Idx*AggSizeInBits;
1177         
1178         NewOffset += BitOffset;
1179       } else if (GEP->getNumOperands() == 3) {
1180         // We know that operand #2 is zero.
1181         unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
1182         const Type *AggTy = AggPtrTy->getElementType();
1183         if (const SequentialType *SeqTy = dyn_cast<SequentialType>(AggTy)) {
1184           unsigned ElSizeBits =
1185             TD.getABITypeSizeInBits(SeqTy->getElementType());
1186
1187           NewOffset += ElSizeBits*Idx;
1188         } else if (const StructType *STy = dyn_cast<StructType>(AggTy)) {
1189           unsigned EltBitOffset =
1190             TD.getStructLayout(STy)->getElementOffsetInBits(Idx);
1191           
1192           NewOffset += EltBitOffset;
1193         } else {
1194           assert(0 && "Unsupported operation!");
1195           abort();
1196         }
1197       } else {
1198         assert(0 && "Unsupported operation!");
1199         abort();
1200       }
1201       ConvertUsesToScalar(GEP, NewAI, NewOffset);
1202       GEP->eraseFromParent();
1203     } else {
1204       assert(0 && "Unsupported operation!");
1205       abort();
1206     }
1207   }
1208 }
1209
1210 /// ConvertUsesOfLoadToScalar - Convert all of the users the specified load to
1211 /// use the new alloca directly, returning the value that should replace the
1212 /// load.  This happens when we are converting an "integer union" to a
1213 /// single integer scalar, or when we are converting a "vector union" to a
1214 /// vector with insert/extractelement instructions.
1215 ///
1216 /// Offset is an offset from the original alloca, in bits that need to be
1217 /// shifted to the right.  By the end of this, there should be no uses of Ptr.
1218 Value *SROA::ConvertUsesOfLoadToScalar(LoadInst *LI, AllocaInst *NewAI, 
1219                                        unsigned Offset) {
1220   // The load is a bit extract from NewAI shifted right by Offset bits.
1221   Value *NV = new LoadInst(NewAI, LI->getName(), LI);
1222   
1223   if (NV->getType() == LI->getType() && Offset == 0) {
1224     // We win, no conversion needed.
1225     return NV;
1226   } 
1227
1228   // If the result type of the 'union' is a pointer, then this must be ptr->ptr
1229   // cast.  Anything else would result in NV being an integer.
1230   if (isa<PointerType>(NV->getType())) {
1231     assert(isa<PointerType>(LI->getType()));
1232     return new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1233   }
1234   
1235   if (const VectorType *VTy = dyn_cast<VectorType>(NV->getType())) {
1236     // If the result alloca is a vector type, this is either an element
1237     // access or a bitcast to another vector type.
1238     if (isa<VectorType>(LI->getType()))
1239       return new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1240
1241     // Otherwise it must be an element access.
1242     const TargetData &TD = getAnalysis<TargetData>();
1243     unsigned Elt = 0;
1244     if (Offset) {
1245       unsigned EltSize = TD.getABITypeSizeInBits(VTy->getElementType());
1246       Elt = Offset/EltSize;
1247       Offset -= EltSize*Elt;
1248     }
1249     NV = new ExtractElementInst(NV, ConstantInt::get(Type::Int32Ty, Elt),
1250                                 "tmp", LI);
1251     
1252     // If we're done, return this element.
1253     if (NV->getType() == LI->getType() && Offset == 0)
1254       return NV;
1255   }
1256   
1257   const IntegerType *NTy = cast<IntegerType>(NV->getType());
1258   
1259   // If this is a big-endian system and the load is narrower than the
1260   // full alloca type, we need to do a shift to get the right bits.
1261   int ShAmt = 0;
1262   const TargetData &TD = getAnalysis<TargetData>();
1263   if (TD.isBigEndian()) {
1264     // On big-endian machines, the lowest bit is stored at the bit offset
1265     // from the pointer given by getTypeStoreSizeInBits.  This matters for
1266     // integers with a bitwidth that is not a multiple of 8.
1267     ShAmt = TD.getTypeStoreSizeInBits(NTy) -
1268     TD.getTypeStoreSizeInBits(LI->getType()) - Offset;
1269   } else {
1270     ShAmt = Offset;
1271   }
1272   
1273   // Note: we support negative bitwidths (with shl) which are not defined.
1274   // We do this to support (f.e.) loads off the end of a structure where
1275   // only some bits are used.
1276   if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
1277     NV = BinaryOperator::CreateLShr(NV, 
1278                                     ConstantInt::get(NV->getType(),ShAmt),
1279                                     LI->getName(), LI);
1280   else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
1281     NV = BinaryOperator::CreateShl(NV, 
1282                                    ConstantInt::get(NV->getType(),-ShAmt),
1283                                    LI->getName(), LI);
1284   
1285   // Finally, unconditionally truncate the integer to the right width.
1286   unsigned LIBitWidth = TD.getTypeSizeInBits(LI->getType());
1287   if (LIBitWidth < NTy->getBitWidth())
1288     NV = new TruncInst(NV, IntegerType::get(LIBitWidth),
1289                        LI->getName(), LI);
1290   
1291   // If the result is an integer, this is a trunc or bitcast.
1292   if (isa<IntegerType>(LI->getType())) {
1293     // Should be done.
1294   } else if (LI->getType()->isFloatingPoint()) {
1295     // Just do a bitcast, we know the sizes match up.
1296     NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1297   } else {
1298     // Otherwise must be a pointer.
1299     NV = new IntToPtrInst(NV, LI->getType(), LI->getName(), LI);
1300   }
1301   assert(NV->getType() == LI->getType() && "Didn't convert right?");
1302   return NV;
1303 }
1304
1305
1306 /// ConvertUsesOfStoreToScalar - Convert the specified store to a load+store
1307 /// pair of the new alloca directly, returning the value that should be stored
1308 /// to the alloca.  This happens when we are converting an "integer union" to a
1309 /// single integer scalar, or when we are converting a "vector union" to a
1310 /// vector with insert/extractelement instructions.
1311 ///
1312 /// Offset is an offset from the original alloca, in bits that need to be
1313 /// shifted to the right.  By the end of this, there should be no uses of Ptr.
1314 Value *SROA::ConvertUsesOfStoreToScalar(StoreInst *SI, AllocaInst *NewAI, 
1315                                         unsigned Offset) {
1316   
1317   // Convert the stored type to the actual type, shift it left to insert
1318   // then 'or' into place.
1319   Value *SV = SI->getOperand(0);
1320   const Type *AllocaType = NewAI->getType()->getElementType();
1321   if (SV->getType() == AllocaType && Offset == 0) {
1322     // All is well.
1323   } else if (const VectorType *PTy = dyn_cast<VectorType>(AllocaType)) {
1324     Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1325     
1326     // If the result alloca is a vector type, this is either an element
1327     // access or a bitcast to another vector type.
1328     if (isa<VectorType>(SV->getType())) {
1329       SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1330     } else {
1331       // Must be an element insertion.
1332       const TargetData &TD = getAnalysis<TargetData>();
1333       unsigned Elt = Offset/TD.getABITypeSizeInBits(PTy->getElementType());
1334       SV = InsertElementInst::Create(Old, SV,
1335                                      ConstantInt::get(Type::Int32Ty, Elt),
1336                                      "tmp", SI);
1337     }
1338   } else if (isa<PointerType>(AllocaType)) {
1339     // If the alloca type is a pointer, then all the elements must be
1340     // pointers.
1341     if (SV->getType() != AllocaType)
1342       SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1343   } else {
1344     Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1345     
1346     // If SV is a float, convert it to the appropriate integer type.
1347     // If it is a pointer, do the same, and also handle ptr->ptr casts
1348     // here.
1349     const TargetData &TD = getAnalysis<TargetData>();
1350     unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
1351     unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
1352     unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
1353     unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
1354     if (SV->getType()->isFloatingPoint())
1355       SV = new BitCastInst(SV, IntegerType::get(SrcWidth),
1356                            SV->getName(), SI);
1357     else if (isa<PointerType>(SV->getType()))
1358       SV = new PtrToIntInst(SV, TD.getIntPtrType(), SV->getName(), SI);
1359     
1360     // Always zero extend the value if needed.
1361     if (SV->getType() != AllocaType)
1362       SV = new ZExtInst(SV, AllocaType, SV->getName(), SI);
1363     
1364     // If this is a big-endian system and the store is narrower than the
1365     // full alloca type, we need to do a shift to get the right bits.
1366     int ShAmt = 0;
1367     if (TD.isBigEndian()) {
1368       // On big-endian machines, the lowest bit is stored at the bit offset
1369       // from the pointer given by getTypeStoreSizeInBits.  This matters for
1370       // integers with a bitwidth that is not a multiple of 8.
1371       ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
1372     } else {
1373       ShAmt = Offset;
1374     }
1375     
1376     // Note: we support negative bitwidths (with shr) which are not defined.
1377     // We do this to support (f.e.) stores off the end of a structure where
1378     // only some bits in the structure are set.
1379     APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1380     if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1381       SV = BinaryOperator::CreateShl(SV, 
1382                                      ConstantInt::get(SV->getType(), ShAmt),
1383                                      SV->getName(), SI);
1384       Mask <<= ShAmt;
1385     } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1386       SV = BinaryOperator::CreateLShr(SV,
1387                                       ConstantInt::get(SV->getType(),-ShAmt),
1388                                       SV->getName(), SI);
1389       Mask = Mask.lshr(ShAmt);
1390     }
1391     
1392     // Mask out the bits we are about to insert from the old value, and or
1393     // in the new bits.
1394     if (SrcWidth != DestWidth) {
1395       assert(DestWidth > SrcWidth);
1396       Old = BinaryOperator::CreateAnd(Old, ConstantInt::get(~Mask),
1397                                       Old->getName()+".mask", SI);
1398       SV = BinaryOperator::CreateOr(Old, SV, SV->getName()+".ins", SI);
1399     }
1400   }
1401   return SV;
1402 }
1403
1404
1405
1406 /// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1407 /// some part of a constant global variable.  This intentionally only accepts
1408 /// constant expressions because we don't can't rewrite arbitrary instructions.
1409 static bool PointsToConstantGlobal(Value *V) {
1410   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1411     return GV->isConstant();
1412   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1413     if (CE->getOpcode() == Instruction::BitCast || 
1414         CE->getOpcode() == Instruction::GetElementPtr)
1415       return PointsToConstantGlobal(CE->getOperand(0));
1416   return false;
1417 }
1418
1419 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1420 /// pointer to an alloca.  Ignore any reads of the pointer, return false if we
1421 /// see any stores or other unknown uses.  If we see pointer arithmetic, keep
1422 /// track of whether it moves the pointer (with isOffset) but otherwise traverse
1423 /// the uses.  If we see a memcpy/memmove that targets an unoffseted pointer to
1424 /// the alloca, and if the source pointer is a pointer to a constant  global, we
1425 /// can optimize this.
1426 static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1427                                            bool isOffset) {
1428   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1429     if (isa<LoadInst>(*UI)) {
1430       // Ignore loads, they are always ok.
1431       continue;
1432     }
1433     if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1434       // If uses of the bitcast are ok, we are ok.
1435       if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1436         return false;
1437       continue;
1438     }
1439     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1440       // If the GEP has all zero indices, it doesn't offset the pointer.  If it
1441       // doesn't, it does.
1442       if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1443                                          isOffset || !GEP->hasAllZeroIndices()))
1444         return false;
1445       continue;
1446     }
1447     
1448     // If this is isn't our memcpy/memmove, reject it as something we can't
1449     // handle.
1450     if (!isa<MemCpyInst>(*UI) && !isa<MemMoveInst>(*UI))
1451       return false;
1452
1453     // If we already have seen a copy, reject the second one.
1454     if (TheCopy) return false;
1455     
1456     // If the pointer has been offset from the start of the alloca, we can't
1457     // safely handle this.
1458     if (isOffset) return false;
1459
1460     // If the memintrinsic isn't using the alloca as the dest, reject it.
1461     if (UI.getOperandNo() != 1) return false;
1462     
1463     MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1464     
1465     // If the source of the memcpy/move is not a constant global, reject it.
1466     if (!PointsToConstantGlobal(MI->getOperand(2)))
1467       return false;
1468     
1469     // Otherwise, the transform is safe.  Remember the copy instruction.
1470     TheCopy = MI;
1471   }
1472   return true;
1473 }
1474
1475 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1476 /// modified by a copy from a constant global.  If we can prove this, we can
1477 /// replace any uses of the alloca with uses of the global directly.
1478 Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocationInst *AI) {
1479   Instruction *TheCopy = 0;
1480   if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1481     return TheCopy;
1482   return 0;
1483 }