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