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