ScalarReplAggregates.cpp revision 202375
150769Sdfr//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
250769Sdfr//
350769Sdfr//                     The LLVM Compiler Infrastructure
450769Sdfr//
550769Sdfr// This file is distributed under the University of Illinois Open Source
650769Sdfr// License. See LICENSE.TXT for details.
750769Sdfr//
850769Sdfr//===----------------------------------------------------------------------===//
950769Sdfr//
1050769Sdfr// This transformation implements the well known scalar replacement of
1150769Sdfr// aggregates transformation.  This xform breaks up alloca instructions of
1250769Sdfr// aggregate type (structure or array) into individual alloca instructions for
1350769Sdfr// each member (if possible).  Then, if possible, it transforms the individual
1450769Sdfr// alloca instructions into nice clean scalar SSA form.
1550769Sdfr//
1650769Sdfr// This combines a simple SRoA algorithm with the Mem2Reg algorithm because
1750769Sdfr// often interact, especially for C++ programs.  As such, iterating between
1850769Sdfr// SRoA, then Mem2Reg until we run out of things to promote works well.
1950769Sdfr//
2050769Sdfr//===----------------------------------------------------------------------===//
2150769Sdfr
2250769Sdfr#define DEBUG_TYPE "scalarrepl"
2350769Sdfr#include "llvm/Transforms/Scalar.h"
2450769Sdfr#include "llvm/Constants.h"
2550769Sdfr#include "llvm/DerivedTypes.h"
2650769Sdfr#include "llvm/Function.h"
2750769Sdfr#include "llvm/GlobalVariable.h"
2850769Sdfr#include "llvm/Instructions.h"
29116181Sobrien#include "llvm/IntrinsicInst.h"
30116181Sobrien#include "llvm/LLVMContext.h"
31116181Sobrien#include "llvm/Pass.h"
3250769Sdfr#include "llvm/Analysis/Dominators.h"
3350769Sdfr#include "llvm/Target/TargetData.h"
3450769Sdfr#include "llvm/Transforms/Utils/PromoteMemToReg.h"
3550769Sdfr#include "llvm/Transforms/Utils/Local.h"
3650769Sdfr#include "llvm/Support/Debug.h"
3750769Sdfr#include "llvm/Support/ErrorHandling.h"
3850769Sdfr#include "llvm/Support/GetElementPtrTypeIterator.h"
3950769Sdfr#include "llvm/Support/IRBuilder.h"
4050769Sdfr#include "llvm/Support/MathExtras.h"
4165176Sdfr#include "llvm/Support/raw_ostream.h"
4250769Sdfr#include "llvm/ADT/SmallVector.h"
4350769Sdfr#include "llvm/ADT/Statistic.h"
44139268Simpusing namespace llvm;
45139268Simp
4650769SdfrSTATISTIC(NumReplaced,  "Number of allocas broken up");
4750769SdfrSTATISTIC(NumPromoted,  "Number of allocas promoted");
4850769SdfrSTATISTIC(NumConverted, "Number of aggregates converted to scalar");
4950769SdfrSTATISTIC(NumGlobals,   "Number of allocas copied from constant global");
5050769Sdfr
5150769Sdfrnamespace {
5250769Sdfr  struct SROA : public FunctionPass {
5350769Sdfr    static char ID; // Pass identification, replacement for typeid
5450769Sdfr    explicit SROA(signed T = -1) : FunctionPass(&ID) {
55139268Simp      if (T == -1)
56139268Simp        SRThreshold = 128;
5750769Sdfr      else
5850769Sdfr        SRThreshold = T;
5962947Stanimura    }
6050769Sdfr
6150769Sdfr    bool runOnFunction(Function &F);
6250769Sdfr
6350769Sdfr    bool performScalarRepl(Function &F);
6450769Sdfr    bool performPromotion(Function &F);
6550769Sdfr
6650769Sdfr    // getAnalysisUsage - This pass does not require any passes, but we know it
6750769Sdfr    // will not alter the CFG, so say so.
6850769Sdfr    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
6950769Sdfr      AU.addRequired<DominatorTree>();
7050769Sdfr      AU.addRequired<DominanceFrontier>();
7150769Sdfr      AU.setPreservesCFG();
7262947Stanimura    }
7362947Stanimura
7462947Stanimura  private:
7562947Stanimura    TargetData *TD;
7662947Stanimura
7762947Stanimura    /// DeadInsts - Keep track of instructions we have made dead, so that
7862947Stanimura    /// we can remove them after we are done working.
7962947Stanimura    SmallVector<Value*, 32> DeadInsts;
8062947Stanimura
8162947Stanimura    /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
8262947Stanimura    /// information about the uses.  All these fields are initialized to false
8362947Stanimura    /// and set to true when something is learned.
8462947Stanimura    struct AllocaInfo {
8562947Stanimura      /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
8662947Stanimura      bool isUnsafe : 1;
8762947Stanimura
8890234Stanimura      /// needsCleanup - This is set to true if there is some use of the alloca
8990234Stanimura      /// that requires cleanup.
9062947Stanimura      bool needsCleanup : 1;
9162947Stanimura
9250769Sdfr      /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
9350769Sdfr      bool isMemCpySrc : 1;
9450769Sdfr
9550769Sdfr      /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
96104142Snyan      bool isMemCpyDst : 1;
97104142Snyan
98104142Snyan      AllocaInfo()
99104142Snyan        : isUnsafe(false), needsCleanup(false),
100104142Snyan          isMemCpySrc(false), isMemCpyDst(false) {}
101104142Snyan    };
102104142Snyan
103104142Snyan    unsigned SRThreshold;
104104142Snyan
105104142Snyan    void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
106104142Snyan
10750769Sdfr    int isSafeAllocaToScalarRepl(AllocaInst *AI);
10850769Sdfr
10950769Sdfr    void isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
11050769Sdfr                             AllocaInfo &Info);
11150769Sdfr    void isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t &Offset,
11250769Sdfr                   AllocaInfo &Info);
11350769Sdfr    void isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
11452241Sdfr                         const Type *MemOpType, bool isStore, AllocaInfo &Info);
115139268Simp    bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
11652241Sdfr    uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
117139268Simp                                  const Type *&IdxTy);
11852241Sdfr
11952241Sdfr    void DoScalarReplacement(AllocaInst *AI,
12052241Sdfr                             std::vector<AllocaInst*> &WorkList);
12152241Sdfr    void DeleteDeadInstructions();
12252241Sdfr    void CleanupAllocaUsers(Value *V);
12352241Sdfr    AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocaInst *Base);
12452241Sdfr
12552241Sdfr    void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
12652241Sdfr                              SmallVector<AllocaInst*, 32> &NewElts);
12752241Sdfr    void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
12852241Sdfr                        SmallVector<AllocaInst*, 32> &NewElts);
12952241Sdfr    void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
13052241Sdfr                    SmallVector<AllocaInst*, 32> &NewElts);
13152241Sdfr    void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
13250769Sdfr                                      AllocaInst *AI,
13350769Sdfr                                      SmallVector<AllocaInst*, 32> &NewElts);
13450769Sdfr    void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
13550769Sdfr                                       SmallVector<AllocaInst*, 32> &NewElts);
13650769Sdfr    void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
13750769Sdfr                                      SmallVector<AllocaInst*, 32> &NewElts);
13850769Sdfr
13950769Sdfr    bool CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
14050769Sdfr                            bool &SawVec, uint64_t Offset, unsigned AllocaSize);
14150769Sdfr    void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
14250769Sdfr    Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
14350769Sdfr                                     uint64_t Offset, IRBuilder<> &Builder);
14450769Sdfr    Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
14550769Sdfr                                     uint64_t Offset, IRBuilder<> &Builder);
14650769Sdfr    static Instruction *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
14750769Sdfr  };
14850769Sdfr}
14950769Sdfr
15050769Sdfrchar SROA::ID = 0;
15150769Sdfrstatic RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
15250769Sdfr
15350769Sdfr// Public interface to the ScalarReplAggregates pass
15450769SdfrFunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
15550769Sdfr  return new SROA(Threshold);
15650769Sdfr}
15750769Sdfr
15850769Sdfr
15950769Sdfrbool SROA::runOnFunction(Function &F) {
16050769Sdfr  TD = getAnalysisIfAvailable<TargetData>();
16150769Sdfr
16250769Sdfr  bool Changed = performPromotion(F);
16350769Sdfr
16450769Sdfr  // FIXME: ScalarRepl currently depends on TargetData more than it
16550769Sdfr  // theoretically needs to. It should be refactored in order to support
16650769Sdfr  // target-independent IR. Until this is done, just skip the actual
16750769Sdfr  // scalar-replacement portion of this pass.
16850769Sdfr  if (!TD) return Changed;
16950769Sdfr
17050769Sdfr  while (1) {
17150769Sdfr    bool LocalChange = performScalarRepl(F);
17250769Sdfr    if (!LocalChange) break;   // No need to repromote if no scalarrepl
17350769Sdfr    Changed = true;
17450769Sdfr    LocalChange = performPromotion(F);
17550769Sdfr    if (!LocalChange) break;   // No need to re-scalarrepl if no promotion
17650769Sdfr  }
17750769Sdfr
17850769Sdfr  return Changed;
17950769Sdfr}
18050769Sdfr
18150769Sdfr
18250769Sdfrbool SROA::performPromotion(Function &F) {
18350769Sdfr  std::vector<AllocaInst*> Allocas;
184139268Simp  DominatorTree         &DT = getAnalysis<DominatorTree>();
18550769Sdfr  DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
18650769Sdfr
18750769Sdfr  BasicBlock &BB = F.getEntryBlock();  // Get the entry node for the function
18850769Sdfr
18950769Sdfr  bool Changed = false;
190139268Simp
19150769Sdfr  while (1) {
19250769Sdfr    Allocas.clear();
19350769Sdfr
19450769Sdfr    // Find allocas that are safe to promote, by looking at all instructions in
19552059Sdfr    // the entry node
19650769Sdfr    for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
19750769Sdfr      if (AllocaInst *AI = dyn_cast<AllocaInst>(I))       // Is it an alloca?
19850769Sdfr        if (isAllocaPromotable(AI))
19950769Sdfr          Allocas.push_back(AI);
20052059Sdfr
20150769Sdfr    if (Allocas.empty()) break;
20250769Sdfr
20352059Sdfr    PromoteMemToReg(Allocas, DT, DF);
20450769Sdfr    NumPromoted += Allocas.size();
20550769Sdfr    Changed = true;
20650769Sdfr  }
20750769Sdfr
20850769Sdfr  return Changed;
20950769Sdfr}
21050769Sdfr
21150769Sdfr/// getNumSAElements - Return the number of elements in the specific struct or
21250769Sdfr/// array.
213139268Simpstatic uint64_t getNumSAElements(const Type *T) {
21450769Sdfr  if (const StructType *ST = dyn_cast<StructType>(T))
21550769Sdfr    return ST->getNumElements();
21650769Sdfr  return cast<ArrayType>(T)->getNumElements();
21750769Sdfr}
21850769Sdfr
21952059Sdfr// performScalarRepl - This algorithm is a simple worklist driven algorithm,
22050769Sdfr// which runs on all of the malloc/alloca instructions in the function, removing
221139268Simp// them if they are only used by getelementptr instructions.
22250769Sdfr//
22350769Sdfrbool SROA::performScalarRepl(Function &F) {
22450769Sdfr  std::vector<AllocaInst*> WorkList;
22550769Sdfr
22650769Sdfr  // Scan the entry basic block, adding any alloca's and mallocs to the worklist
22750769Sdfr  BasicBlock &BB = F.getEntryBlock();
22850769Sdfr  for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
22950769Sdfr    if (AllocaInst *A = dyn_cast<AllocaInst>(I))
23050769Sdfr      WorkList.push_back(A);
23150769Sdfr
23250769Sdfr  // Process the worklist
23350769Sdfr  bool Changed = false;
23450769Sdfr  while (!WorkList.empty()) {
23550769Sdfr    AllocaInst *AI = WorkList.back();
23650769Sdfr    WorkList.pop_back();
23750769Sdfr
23850769Sdfr    // Handle dead allocas trivially.  These can be formed by SROA'ing arrays
23950769Sdfr    // with unused elements.
24050769Sdfr    if (AI->use_empty()) {
24150769Sdfr      AI->eraseFromParent();
24250769Sdfr      continue;
24350769Sdfr    }
24450769Sdfr
24550769Sdfr    // If this alloca is impossible for us to promote, reject it early.
24650769Sdfr    if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
24750769Sdfr      continue;
24866840Smsmith
24966840Smsmith    // Check to see if this allocation is only modified by a memcpy/memmove from
25066840Smsmith    // a constant global.  If this is the case, we can change all users to use
251139268Simp    // the constant global instead.  This is commonly produced by the CFE by
252139268Simp    // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
253139268Simp    // is only subsequently read.
25466840Smsmith    if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
25566840Smsmith      DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
256139268Simp      DEBUG(dbgs() << "  memcpy = " << *TheCopy << '\n');
257139268Simp      Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
258139268Simp      AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
25966840Smsmith      TheCopy->eraseFromParent();  // Don't mutate the global.
26066840Smsmith      AI->eraseFromParent();
261139268Simp      ++NumGlobals;
262139268Simp      Changed = true;
263139268Simp      continue;
26466840Smsmith    }
26566840Smsmith
266139268Simp    // Check to see if we can perform the core SROA transformation.  We cannot
267139268Simp    // transform the allocation instruction if it is an array allocation
268139268Simp    // (allocations OF arrays are ok though), and an allocation of a scalar
26966840Smsmith    // value cannot be decomposed at all.
27066840Smsmith    uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
27166840Smsmith
27250769Sdfr    // Do not promote [0 x %struct].
27350769Sdfr    if (AllocaSize == 0) continue;
27450769Sdfr
275139268Simp    // Do not promote any struct whose size is too big.
276139268Simp    if (AllocaSize > SRThreshold) continue;
27783051Syokota
27883051Syokota    if ((isa<StructType>(AI->getAllocatedType()) ||
27983051Syokota         isa<ArrayType>(AI->getAllocatedType())) &&
28083051Syokota        // Do not promote any struct into more than "32" separate vars.
28183051Syokota        getNumSAElements(AI->getAllocatedType()) <= SRThreshold/4) {
28283051Syokota      // Check that all of the users of the allocation are capable of being
28383051Syokota      // transformed.
28483051Syokota      switch (isSafeAllocaToScalarRepl(AI)) {
28583051Syokota      default: llvm_unreachable("Unexpected value!");
28683051Syokota      case 0:  // Not safe to scalar replace.
28783051Syokota        break;
28883051Syokota      case 1:  // Safe, but requires cleanup/canonicalizations first
28983051Syokota        CleanupAllocaUsers(AI);
29083051Syokota        // FALL THROUGH.
29183051Syokota      case 3:  // Safe to scalar replace.
29283051Syokota        DoScalarReplacement(AI, WorkList);
29383051Syokota        Changed = true;
29450769Sdfr        continue;
29566840Smsmith      }
29650769Sdfr    }
29750769Sdfr
29850769Sdfr    // If we can turn this aggregate value (potentially with casts) into a
29950769Sdfr    // simple scalar value that can be mem2reg'd into a register value.
30050769Sdfr    // IsNotTrivial tracks whether this is something that mem2reg could have
30150769Sdfr    // promoted itself.  If so, we don't want to transform it needlessly.  Note
30250769Sdfr    // that we can't just check based on the type: the alloca may be of an i32
303139268Simp    // but that has pointer arithmetic to set byte 3 of it or something.
30483051Syokota    bool IsNotTrivial = false;
30583051Syokota    const Type *VectorTy = 0;
30683051Syokota    bool HadAVector = false;
30783051Syokota    if (CanConvertToScalar(AI, IsNotTrivial, VectorTy, HadAVector,
30883051Syokota                           0, unsigned(AllocaSize)) && IsNotTrivial) {
30983051Syokota      AllocaInst *NewAI;
31083051Syokota      // If we were able to find a vector type that can handle this with
31183051Syokota      // insert/extract elements, and if there was at least one use that had
31283051Syokota      // a vector type, promote this to a vector.  We don't want to promote
31350769Sdfr      // random stuff that doesn't use vectors (e.g. <9 x double>) because then
31466840Smsmith      // we just get a lot of insert/extracts.  If at least one vector is
31550769Sdfr      // involved, then we probably really do have a union of vector/array.
31650769Sdfr      if (VectorTy && isa<VectorType>(VectorTy) && HadAVector) {
31750769Sdfr        DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n  TYPE = "
31850769Sdfr                     << *VectorTy << '\n');
31950769Sdfr
32083051Syokota        // Create and insert the vector alloca.
32183051Syokota        NewAI = new AllocaInst(VectorTy, 0, "",  AI->getParent()->begin());
32283051Syokota        ConvertUsesToScalar(AI, NewAI, 0);
32383051Syokota      } else {
32483051Syokota        DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
32583051Syokota
32683051Syokota        // Create and insert the integer alloca.
32783051Syokota        const Type *NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
32883051Syokota        NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
32983051Syokota        ConvertUsesToScalar(AI, NewAI, 0);
33083051Syokota      }
33150769Sdfr      NewAI->takeName(AI);
33266840Smsmith      AI->eraseFromParent();
33350769Sdfr      ++NumConverted;
33450769Sdfr      Changed = true;
33550769Sdfr      continue;
33650769Sdfr    }
33750769Sdfr
33883051Syokota    // Otherwise, couldn't process this alloca.
33950769Sdfr  }
34050769Sdfr
34150769Sdfr  return Changed;
34283051Syokota}
34383051Syokota
34483051Syokota/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
34583051Syokota/// predicate, do SROA now.
34683051Syokotavoid SROA::DoScalarReplacement(AllocaInst *AI,
34783051Syokota                               std::vector<AllocaInst*> &WorkList) {
34883051Syokota  DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
34983051Syokota  SmallVector<AllocaInst*, 32> ElementAllocas;
35050769Sdfr  if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
35166840Smsmith    ElementAllocas.reserve(ST->getNumContainedTypes());
35250769Sdfr    for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
35350769Sdfr      AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
35450769Sdfr                                      AI->getAlignment(),
35550769Sdfr                                      AI->getName() + "." + Twine(i), AI);
35650769Sdfr      ElementAllocas.push_back(NA);
35750769Sdfr      WorkList.push_back(NA);  // Add to worklist for recursive processing
35850769Sdfr    }
35950769Sdfr  } else {
36050769Sdfr    const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
36150769Sdfr    ElementAllocas.reserve(AT->getNumElements());
36250769Sdfr    const Type *ElTy = AT->getElementType();
36350769Sdfr    for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
36450769Sdfr      AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
36550769Sdfr                                      AI->getName() + "." + Twine(i), AI);
36650769Sdfr      ElementAllocas.push_back(NA);
36750769Sdfr      WorkList.push_back(NA);  // Add to worklist for recursive processing
36850769Sdfr    }
36950769Sdfr  }
37062947Stanimura
371139268Simp  // Now that we have created the new alloca instructions, rewrite all the
372139268Simp  // uses of the old alloca.
37350769Sdfr  RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
37450769Sdfr
37550769Sdfr  // Now erase any instructions that were made dead while rewriting the alloca.
37650769Sdfr  DeleteDeadInstructions();
37750769Sdfr  AI->eraseFromParent();
378139268Simp
37950769Sdfr  NumReplaced++;
38050769Sdfr}
38150769Sdfr
38250769Sdfr/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
38350769Sdfr/// recursively including all their operands that become trivially dead.
38462947Stanimuravoid SROA::DeleteDeadInstructions() {
38562947Stanimura  while (!DeadInsts.empty()) {
38662947Stanimura    Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
38762947Stanimura
38862947Stanimura    for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
38962947Stanimura      if (Instruction *U = dyn_cast<Instruction>(*OI)) {
39062947Stanimura        // Zero out the operand and see if it becomes trivially dead.
39162947Stanimura        // (But, don't add allocas to the dead instruction list -- they are
39262947Stanimura        // already on the worklist and will be deleted separately.)
39362947Stanimura        *OI = 0;
39462947Stanimura        if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
39562947Stanimura          DeadInsts.push_back(U);
39662947Stanimura      }
39762947Stanimura
39862947Stanimura    I->eraseFromParent();
39962947Stanimura  }
40050769Sdfr}
40150769Sdfr
40250769Sdfr/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
40350769Sdfr/// performing scalar replacement of alloca AI.  The results are flagged in
40450769Sdfr/// the Info parameter.  Offset indicates the position within AI that is
40550769Sdfr/// referenced by this instruction.
40650769Sdfrvoid SROA::isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
40750769Sdfr                               AllocaInfo &Info) {
40850769Sdfr  for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
40952059Sdfr    Instruction *User = cast<Instruction>(*UI);
41050769Sdfr
41150769Sdfr    if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
41250769Sdfr      isSafeForScalarRepl(BC, AI, Offset, Info);
41352059Sdfr    } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
414139268Simp      uint64_t GEPOffset = Offset;
41550769Sdfr      isSafeGEP(GEPI, AI, GEPOffset, Info);
41652059Sdfr      if (!Info.isUnsafe)
41752059Sdfr        isSafeForScalarRepl(GEPI, AI, GEPOffset, Info);
418139268Simp    } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
41950769Sdfr      ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
42050769Sdfr      if (Length)
42150769Sdfr        isSafeMemAccess(AI, Offset, Length->getZExtValue(), 0,
42252059Sdfr                        UI.getOperandNo() == 1, Info);
42350769Sdfr      else
42450769Sdfr        MarkUnsafe(Info);
42552059Sdfr    } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
42652059Sdfr      if (!LI->isVolatile()) {
42752059Sdfr        const Type *LIType = LI->getType();
42852059Sdfr        isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(LIType),
42952059Sdfr                        LIType, false, Info);
43052059Sdfr      } else
43152059Sdfr        MarkUnsafe(Info);
43250769Sdfr    } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
43350769Sdfr      // Store is ok if storing INTO the pointer, not storing the pointer
43450769Sdfr      if (!SI->isVolatile() && SI->getOperand(0) != I) {
43552059Sdfr        const Type *SIType = SI->getOperand(0)->getType();
43652059Sdfr        isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(SIType),
43750769Sdfr                        SIType, true, Info);
43852059Sdfr      } else
43950769Sdfr        MarkUnsafe(Info);
44050769Sdfr    } else if (isa<DbgInfoIntrinsic>(UI)) {
44150769Sdfr      // If one user is DbgInfoIntrinsic then check if all users are
44252059Sdfr      // DbgInfoIntrinsics.
44352059Sdfr      if (OnlyUsedByDbgInfoIntrinsics(I)) {
44452059Sdfr        Info.needsCleanup = true;
44550769Sdfr        return;
44650769Sdfr      }
44783504Syokota      MarkUnsafe(Info);
44883504Syokota    } else {
44983504Syokota      DEBUG(errs() << "  Transformation preventing inst: " << *User << '\n');
45083504Syokota      MarkUnsafe(Info);
45183504Syokota    }
45283504Syokota    if (Info.isUnsafe) return;
45383504Syokota  }
45483504Syokota}
45583504Syokota
45652059Sdfr/// isSafeGEP - Check if a GEP instruction can be handled for scalar
45752059Sdfr/// replacement.  It is safe when all the indices are constant, in-bounds
45852059Sdfr/// references, and when the resulting offset corresponds to an element within
45952059Sdfr/// the alloca type.  The results are flagged in the Info parameter.  Upon
46050769Sdfr/// return, Offset is adjusted as specified by the GEP indices.
46152059Sdfrvoid SROA::isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI,
46250769Sdfr                     uint64_t &Offset, AllocaInfo &Info) {
46352059Sdfr  gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
46452059Sdfr  if (GEPIt == E)
46552059Sdfr    return;
46652059Sdfr
46750769Sdfr  // Walk through the GEP type indices, checking the types that this indexes
46850769Sdfr  // into.
46950769Sdfr  for (; GEPIt != E; ++GEPIt) {
47052059Sdfr    // Ignore struct elements, no extra checking needed for these.
47152059Sdfr    if (isa<StructType>(*GEPIt))
47252059Sdfr      continue;
47352059Sdfr
47452059Sdfr    ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
47552059Sdfr    if (!IdxVal)
47652059Sdfr      return MarkUnsafe(Info);
47752059Sdfr  }
47852059Sdfr
47952059Sdfr  // Compute the offset due to this GEP and check if the alloca has a
48052059Sdfr  // component element at that offset.
48152059Sdfr  SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
48252059Sdfr  Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
48352059Sdfr                                 &Indices[0], Indices.size());
48452059Sdfr  if (!TypeHasComponent(AI->getAllocatedType(), Offset, 0))
48552059Sdfr    MarkUnsafe(Info);
48652059Sdfr}
48752059Sdfr
48852059Sdfr/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
48952059Sdfr/// alloca or has an offset and size that corresponds to a component element
490139268Simp/// within it.  The offset checked here may have been formed from a GEP with a
49152059Sdfr/// pointer bitcasted to a different type.
49252059Sdfrvoid SROA::isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
49350769Sdfr                           const Type *MemOpType, bool isStore,
49450769Sdfr                           AllocaInfo &Info) {
49552059Sdfr  // Check if this is a load/store of the entire alloca.
49652059Sdfr  if (Offset == 0 && MemSize == TD->getTypeAllocSize(AI->getAllocatedType())) {
49752059Sdfr    bool UsesAggregateType = (MemOpType == AI->getAllocatedType());
49852059Sdfr    // This is safe for MemIntrinsics (where MemOpType is 0), integer types
49952059Sdfr    // (which are essentially the same as the MemIntrinsics, especially with
50062947Stanimura    // regard to copying padding between elements), or references using the
50152059Sdfr    // aggregate type of the alloca.
50252059Sdfr    if (!MemOpType || isa<IntegerType>(MemOpType) || UsesAggregateType) {
50352059Sdfr      if (!UsesAggregateType) {
50483504Syokota        if (isStore)
50583504Syokota          Info.isMemCpyDst = true;
506139268Simp        else
50752059Sdfr          Info.isMemCpySrc = true;
50852059Sdfr      }
50952059Sdfr      return;
51083051Syokota    }
511139268Simp  }
51252059Sdfr  // Check if the offset/size correspond to a component within the alloca type.
51352059Sdfr  const Type *T = AI->getAllocatedType();
514139268Simp  if (TypeHasComponent(T, Offset, MemSize))
51550769Sdfr    return;
51652059Sdfr
51750769Sdfr  return MarkUnsafe(Info);
51852059Sdfr}
51952059Sdfr
520139268Simp/// TypeHasComponent - Return true if T has a component type with the
521139268Simp/// specified offset and size.  If Size is zero, do not check the size.
52252059Sdfrbool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
52352059Sdfr  const Type *EltTy;
52452059Sdfr  uint64_t EltSize;
52552059Sdfr  if (const StructType *ST = dyn_cast<StructType>(T)) {
52652059Sdfr    const StructLayout *Layout = TD->getStructLayout(ST);
52752059Sdfr    unsigned EltIdx = Layout->getElementContainingOffset(Offset);
528139268Simp    EltTy = ST->getContainedType(EltIdx);
52950769Sdfr    EltSize = TD->getTypeAllocSize(EltTy);
53050769Sdfr    Offset -= Layout->getElementOffset(EltIdx);
53150769Sdfr  } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
53252059Sdfr    EltTy = AT->getElementType();
533139268Simp    EltSize = TD->getTypeAllocSize(EltTy);
53452059Sdfr    if (Offset >= AT->getNumElements() * EltSize)
53552059Sdfr      return false;
53652059Sdfr    Offset %= EltSize;
53752059Sdfr  } else {
53850769Sdfr    return false;
53952059Sdfr  }
54052059Sdfr  if (Offset == 0 && (Size == 0 || EltSize == Size))
54152059Sdfr    return true;
54250769Sdfr  // Check if the component spans multiple elements.
54350769Sdfr  if (Offset + Size > EltSize)
54450769Sdfr    return false;
545139268Simp  return TypeHasComponent(EltTy, Offset, Size);
54650769Sdfr}
54750769Sdfr
54850769Sdfr/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
54952059Sdfr/// the instruction I, which references it, to use the separate elements.
55052059Sdfr/// Offset indicates the position within AI that is referenced by this
55152059Sdfr/// instruction.
55252059Sdfrvoid SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
55352059Sdfr                                SmallVector<AllocaInst*, 32> &NewElts) {
55452059Sdfr  for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
555105226Sphk    Instruction *User = cast<Instruction>(*UI);
556105226Sphk
557105226Sphk    if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
558105226Sphk      RewriteBitCast(BC, AI, Offset, NewElts);
55952059Sdfr    } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
56052059Sdfr      RewriteGEP(GEPI, AI, Offset, NewElts);
56152059Sdfr    } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
56252059Sdfr      ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
56352059Sdfr      uint64_t MemSize = Length->getZExtValue();
56452059Sdfr      if (Offset == 0 &&
56552059Sdfr          MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
56652059Sdfr        RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
56752059Sdfr      // Otherwise the intrinsic can only touch a single element and the
56852059Sdfr      // address operand will be updated, so nothing else needs to be done.
56952059Sdfr    } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
57052059Sdfr      const Type *LIType = LI->getType();
57152059Sdfr      if (LIType == AI->getAllocatedType()) {
572139268Simp        // Replace:
57352059Sdfr        //   %res = load { i32, i32 }* %alloc
57452059Sdfr        // with:
57552059Sdfr        //   %load.0 = load i32* %alloc.0
57652059Sdfr        //   %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
57752059Sdfr        //   %load.1 = load i32* %alloc.1
57852059Sdfr        //   %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
57952059Sdfr        // (Also works for arrays instead of structs)
580115543Sphk        Value *Insert = UndefValue::get(LIType);
581115543Sphk        for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
582139268Simp          Value *Load = new LoadInst(NewElts[i], "load", LI);
583115543Sphk          Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
58452059Sdfr        }
58552059Sdfr        LI->replaceAllUsesWith(Insert);
58652059Sdfr        DeadInsts.push_back(LI);
58752059Sdfr      } else if (isa<IntegerType>(LIType) &&
58852059Sdfr                 TD->getTypeAllocSize(LIType) ==
58952059Sdfr                 TD->getTypeAllocSize(AI->getAllocatedType())) {
59052059Sdfr        // If this is a load of the entire alloca to an integer, rewrite it.
591139268Simp        RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
59252059Sdfr      }
59352059Sdfr    } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
59452059Sdfr      Value *Val = SI->getOperand(0);
59552059Sdfr      const Type *SIType = Val->getType();
59652059Sdfr      if (SIType == AI->getAllocatedType()) {
59752059Sdfr        // Replace:
598139268Simp        //   store { i32, i32 } %val, { i32, i32 }* %alloc
59952059Sdfr        // with:
60052059Sdfr        //   %val.0 = extractvalue { i32, i32 } %val, 0
60152059Sdfr        //   store i32 %val.0, i32* %alloc.0
60252059Sdfr        //   %val.1 = extractvalue { i32, i32 } %val, 1
60352059Sdfr        //   store i32 %val.1, i32* %alloc.1
60452059Sdfr        // (Also works for arrays instead of structs)
60552059Sdfr        for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
60652059Sdfr          Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
60752059Sdfr          new StoreInst(Extract, NewElts[i], SI);
60852059Sdfr        }
60952059Sdfr        DeadInsts.push_back(SI);
61052059Sdfr      } else if (isa<IntegerType>(SIType) &&
61152059Sdfr                 TD->getTypeAllocSize(SIType) ==
61252059Sdfr                 TD->getTypeAllocSize(AI->getAllocatedType())) {
61352059Sdfr        // If this is a store of the entire alloca from an integer, rewrite it.
61452059Sdfr        RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
61552059Sdfr      }
61652059Sdfr    }
61752059Sdfr  }
61852059Sdfr}
61952059Sdfr
62052059Sdfr/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
62152059Sdfr/// and recursively continue updating all of its uses.
62252059Sdfrvoid SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
62352059Sdfr                          SmallVector<AllocaInst*, 32> &NewElts) {
62452059Sdfr  RewriteForScalarRepl(BC, AI, Offset, NewElts);
62552059Sdfr  if (BC->getOperand(0) != AI)
62652059Sdfr    return;
62752059Sdfr
62852059Sdfr  // The bitcast references the original alloca.  Replace its uses with
629139268Simp  // references to the first new element alloca.
63052059Sdfr  Instruction *Val = NewElts[0];
63152059Sdfr  if (Val->getType() != BC->getDestTy()) {
63252059Sdfr    Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
63352059Sdfr    Val->takeName(BC);
63452059Sdfr  }
63552059Sdfr  BC->replaceAllUsesWith(Val);
63652059Sdfr  DeadInsts.push_back(BC);
63752059Sdfr}
63852059Sdfr
63952059Sdfr/// FindElementAndOffset - Return the index of the element containing Offset
64052059Sdfr/// within the specified type, which must be either a struct or an array.
64152059Sdfr/// Sets T to the type of the element and Offset to the offset within that
642139268Simp/// element.  IdxTy is set to the type of the index result to be used in a
643139268Simp/// GEP instruction.
64452059Sdfruint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
64552059Sdfr                                    const Type *&IdxTy) {
64652059Sdfr  uint64_t Idx = 0;
64752059Sdfr  if (const StructType *ST = dyn_cast<StructType>(T)) {
64852059Sdfr    const StructLayout *Layout = TD->getStructLayout(ST);
64952059Sdfr    Idx = Layout->getElementContainingOffset(Offset);
65052059Sdfr    T = ST->getContainedType(Idx);
65152059Sdfr    Offset -= Layout->getElementOffset(Idx);
65252059Sdfr    IdxTy = Type::getInt32Ty(T->getContext());
653139268Simp    return Idx;
65452059Sdfr  }
65552059Sdfr  const ArrayType *AT = cast<ArrayType>(T);
65652059Sdfr  T = AT->getElementType();
65750769Sdfr  uint64_t EltSize = TD->getTypeAllocSize(T);
65850769Sdfr  Idx = Offset / EltSize;
65950769Sdfr  Offset -= Idx * EltSize;
66050769Sdfr  IdxTy = Type::getInt64Ty(T->getContext());
66150769Sdfr  return Idx;
66250769Sdfr}
66350769Sdfr
66450769Sdfr/// RewriteGEP - Check if this GEP instruction moves the pointer across
66550769Sdfr/// elements of the alloca that are being split apart, and if so, rewrite
66650769Sdfr/// the GEP to be relative to the new element.
66750769Sdfrvoid SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
66850769Sdfr                      SmallVector<AllocaInst*, 32> &NewElts) {
66950769Sdfr  uint64_t OldOffset = Offset;
67050769Sdfr  SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
67152059Sdfr  Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
67252059Sdfr                                 &Indices[0], Indices.size());
67352059Sdfr
67452059Sdfr  RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
675104142Snyan
676104142Snyan  const Type *T = AI->getAllocatedType();
677104142Snyan  const Type *IdxTy;
678104142Snyan  uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
67950769Sdfr  if (GEPI->getOperand(0) == AI)
68050769Sdfr    OldIdx = ~0ULL; // Force the GEP to be rewritten.
68150769Sdfr
68250769Sdfr  T = AI->getAllocatedType();
68350769Sdfr  uint64_t EltOffset = Offset;
68450769Sdfr  uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
68550769Sdfr
68650769Sdfr  // If this GEP does not move the pointer across elements of the alloca
68750769Sdfr  // being split, then it does not needs to be rewritten.
68850769Sdfr  if (Idx == OldIdx)
68950769Sdfr    return;
69050769Sdfr
69150769Sdfr  const Type *i32Ty = Type::getInt32Ty(AI->getContext());
69250769Sdfr  SmallVector<Value*, 8> NewArgs;
69350769Sdfr  NewArgs.push_back(Constant::getNullValue(i32Ty));
69450769Sdfr  while (EltOffset != 0) {
69550769Sdfr    uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
69650769Sdfr    NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
69750769Sdfr  }
69850769Sdfr  Instruction *Val = NewElts[Idx];
69950769Sdfr  if (NewArgs.size() > 1) {
70050769Sdfr    Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
70150769Sdfr                                            NewArgs.end(), "", GEPI);
70250769Sdfr    Val->takeName(GEPI);
70350769Sdfr  }
70450769Sdfr  if (Val->getType() != GEPI->getType())
70550769Sdfr    Val = new BitCastInst(Val, GEPI->getType(), Val->getNameStr(), GEPI);
70650769Sdfr  GEPI->replaceAllUsesWith(Val);
70750769Sdfr  DeadInsts.push_back(GEPI);
70850769Sdfr}
70950769Sdfr
71050769Sdfr/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
71150769Sdfr/// Rewrite it to copy or set the elements of the scalarized memory.
71250769Sdfrvoid SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
71352059Sdfr                                        AllocaInst *AI,
71450769Sdfr                                        SmallVector<AllocaInst*, 32> &NewElts) {
71550769Sdfr  // If this is a memcpy/memmove, construct the other pointer as the
71650769Sdfr  // appropriate type.  The "Other" pointer is the pointer that goes to memory
71750769Sdfr  // that doesn't have anything to do with the alloca that we are promoting. For
71850769Sdfr  // memset, this Value* stays null.
71950769Sdfr  Value *OtherPtr = 0;
720104142Snyan  LLVMContext &Context = MI->getContext();
721104142Snyan  unsigned MemAlignment = MI->getAlignment();
722104142Snyan  if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
723104142Snyan    if (Inst == MTI->getRawDest())
724104142Snyan      OtherPtr = MTI->getRawSource();
725104142Snyan    else {
726104142Snyan      assert(Inst == MTI->getRawSource());
727104142Snyan      OtherPtr = MTI->getRawDest();
728104142Snyan    }
729104142Snyan  }
730104142Snyan
731104142Snyan  // If there is an other pointer, we want to convert it to the same pointer
732139268Simp  // type as AI has, so we can GEP through it safely.
733139268Simp  if (OtherPtr) {
734104142Snyan
735104142Snyan    // Remove bitcasts and all-zero GEPs from OtherPtr.  This is an
736104142Snyan    // optimization, but it's also required to detect the corner case where
737104142Snyan    // both pointer operands are referencing the same memory, and where
738139268Simp    // OtherPtr may be a bitcast or GEP that currently being rewritten.  (This
739139268Simp    // function is only called for mem intrinsics that access the whole
740104142Snyan    // aggregate, so non-zero GEPs are not an issue here.)
741104142Snyan    while (1) {
742104142Snyan      if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr)) {
743139268Simp        OtherPtr = BC->getOperand(0);
744104142Snyan        continue;
745139268Simp      }
74652059Sdfr      if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr)) {
74752059Sdfr        // All zero GEPs are effectively bitcasts.
748139268Simp        if (GEP->hasAllZeroIndices()) {
74950769Sdfr          OtherPtr = GEP->getOperand(0);
75050769Sdfr          continue;
75150769Sdfr        }
75250769Sdfr      }
75350769Sdfr      break;
75450769Sdfr    }
75550769Sdfr    // If OtherPtr has already been rewritten, this intrinsic will be dead.
75650769Sdfr    if (OtherPtr == NewElts[0])
75750769Sdfr      return;
75850769Sdfr
75950769Sdfr    if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
76050769Sdfr      if (BCE->getOpcode() == Instruction::BitCast)
76150769Sdfr        OtherPtr = BCE->getOperand(0);
76250769Sdfr
76350769Sdfr    // If the pointer is not the right type, insert a bitcast to the right
76450769Sdfr    // type.
76550769Sdfr    if (OtherPtr->getType() != AI->getType())
76650769Sdfr      OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
76750769Sdfr                                 MI);
76852059Sdfr  }
76952059Sdfr
77052059Sdfr  // Process each element of the aggregate.
77152059Sdfr  Value *TheFn = MI->getOperand(0);
77252059Sdfr  const Type *BytePtrTy = MI->getRawDest()->getType();
77352059Sdfr  bool SROADest = MI->getRawDest() == Inst;
774139268Simp
77550769Sdfr  Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
77650769Sdfr
77750769Sdfr  for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
77850769Sdfr    // If this is a memcpy/memmove, emit a GEP of the other element address.
77950769Sdfr    Value *OtherElt = 0;
78050769Sdfr    unsigned OtherEltAlign = MemAlignment;
78150769Sdfr
78250769Sdfr    if (OtherPtr == AI) {
78350769Sdfr      OtherElt = NewElts[i];
78450769Sdfr      OtherEltAlign = 0;
78550769Sdfr    } else if (OtherPtr) {
78650769Sdfr      Value *Idx[2] = { Zero,
78750769Sdfr                      ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
78850769Sdfr      OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
78950769Sdfr                                           OtherPtr->getNameStr()+"."+Twine(i),
79050769Sdfr                                                   MI);
79150769Sdfr      uint64_t EltOffset;
79250769Sdfr      const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
79350769Sdfr      if (const StructType *ST =
79450769Sdfr            dyn_cast<StructType>(OtherPtrTy->getElementType())) {
79550769Sdfr        EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
796139271Simp      } else {
797139268Simp        const Type *EltTy =
79850769Sdfr          cast<SequentialType>(OtherPtr->getType())->getElementType();
79950769Sdfr        EltOffset = TD->getTypeAllocSize(EltTy)*i;
80050769Sdfr      }
80150769Sdfr
80250769Sdfr      // The alignment of the other pointer is the guaranteed alignment of the
803139269Simp      // element, which is affected by both the known alignment of the whole
804139269Simp      // mem intrinsic and the alignment of the element.  If the alignment of
80550769Sdfr      // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
80650769Sdfr      // known alignment is just 4 bytes.
80750769Sdfr      OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
80850769Sdfr    }
80950769Sdfr
81050769Sdfr    Value *EltPtr = NewElts[i];
81150769Sdfr    const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
81250769Sdfr
81350769Sdfr    // If we got down to a scalar, insert a load or store as appropriate.
81450769Sdfr    if (EltTy->isSingleValueType()) {
81550769Sdfr      if (isa<MemTransferInst>(MI)) {
81650769Sdfr        if (SROADest) {
81750769Sdfr          // From Other to Alloca.
81850769Sdfr          Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
81950769Sdfr          new StoreInst(Elt, EltPtr, MI);
82050769Sdfr        } else {
82150769Sdfr          // From Alloca to Other.
82250769Sdfr          Value *Elt = new LoadInst(EltPtr, "tmp", MI);
823          new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
824        }
825        continue;
826      }
827      assert(isa<MemSetInst>(MI));
828
829      // If the stored element is zero (common case), just store a null
830      // constant.
831      Constant *StoreVal;
832      if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
833        if (CI->isZero()) {
834          StoreVal = Constant::getNullValue(EltTy);  // 0.0, null, 0, <0,0>
835        } else {
836          // If EltTy is a vector type, get the element type.
837          const Type *ValTy = EltTy->getScalarType();
838
839          // Construct an integer with the right value.
840          unsigned EltSize = TD->getTypeSizeInBits(ValTy);
841          APInt OneVal(EltSize, CI->getZExtValue());
842          APInt TotalVal(OneVal);
843          // Set each byte.
844          for (unsigned i = 0; 8*i < EltSize; ++i) {
845            TotalVal = TotalVal.shl(8);
846            TotalVal |= OneVal;
847          }
848
849          // Convert the integer value to the appropriate type.
850          StoreVal = ConstantInt::get(Context, TotalVal);
851          if (isa<PointerType>(ValTy))
852            StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
853          else if (ValTy->isFloatingPoint())
854            StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
855          assert(StoreVal->getType() == ValTy && "Type mismatch!");
856
857          // If the requested value was a vector constant, create it.
858          if (EltTy != ValTy) {
859            unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
860            SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
861            StoreVal = ConstantVector::get(&Elts[0], NumElts);
862          }
863        }
864        new StoreInst(StoreVal, EltPtr, MI);
865        continue;
866      }
867      // Otherwise, if we're storing a byte variable, use a memset call for
868      // this element.
869    }
870
871    // Cast the element pointer to BytePtrTy.
872    if (EltPtr->getType() != BytePtrTy)
873      EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
874
875    // Cast the other pointer (if we have one) to BytePtrTy.
876    if (OtherElt && OtherElt->getType() != BytePtrTy)
877      OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
878                                 MI);
879
880    unsigned EltSize = TD->getTypeAllocSize(EltTy);
881
882    // Finally, insert the meminst for this element.
883    if (isa<MemTransferInst>(MI)) {
884      Value *Ops[] = {
885        SROADest ? EltPtr : OtherElt,  // Dest ptr
886        SROADest ? OtherElt : EltPtr,  // Src ptr
887        ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
888        // Align
889        ConstantInt::get(Type::getInt32Ty(MI->getContext()), OtherEltAlign)
890      };
891      CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
892    } else {
893      assert(isa<MemSetInst>(MI));
894      Value *Ops[] = {
895        EltPtr, MI->getOperand(2),  // Dest, Value,
896        ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
897        Zero  // Align
898      };
899      CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
900    }
901  }
902  DeadInsts.push_back(MI);
903}
904
905/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
906/// overwrites the entire allocation.  Extract out the pieces of the stored
907/// integer and store them individually.
908void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
909                                         SmallVector<AllocaInst*, 32> &NewElts){
910  // Extract each element out of the integer according to its structure offset
911  // and store the element value to the individual alloca.
912  Value *SrcVal = SI->getOperand(0);
913  const Type *AllocaEltTy = AI->getAllocatedType();
914  uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
915
916  // Handle tail padding by extending the operand
917  if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
918    SrcVal = new ZExtInst(SrcVal,
919                          IntegerType::get(SI->getContext(), AllocaSizeBits),
920                          "", SI);
921
922  DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
923               << '\n');
924
925  // There are two forms here: AI could be an array or struct.  Both cases
926  // have different ways to compute the element offset.
927  if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
928    const StructLayout *Layout = TD->getStructLayout(EltSTy);
929
930    for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
931      // Get the number of bits to shift SrcVal to get the value.
932      const Type *FieldTy = EltSTy->getElementType(i);
933      uint64_t Shift = Layout->getElementOffsetInBits(i);
934
935      if (TD->isBigEndian())
936        Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
937
938      Value *EltVal = SrcVal;
939      if (Shift) {
940        Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
941        EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
942                                            "sroa.store.elt", SI);
943      }
944
945      // Truncate down to an integer of the right size.
946      uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
947
948      // Ignore zero sized fields like {}, they obviously contain no data.
949      if (FieldSizeBits == 0) continue;
950
951      if (FieldSizeBits != AllocaSizeBits)
952        EltVal = new TruncInst(EltVal,
953                             IntegerType::get(SI->getContext(), FieldSizeBits),
954                              "", SI);
955      Value *DestField = NewElts[i];
956      if (EltVal->getType() == FieldTy) {
957        // Storing to an integer field of this size, just do it.
958      } else if (FieldTy->isFloatingPoint() || isa<VectorType>(FieldTy)) {
959        // Bitcast to the right element type (for fp/vector values).
960        EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
961      } else {
962        // Otherwise, bitcast the dest pointer (for aggregates).
963        DestField = new BitCastInst(DestField,
964                              PointerType::getUnqual(EltVal->getType()),
965                                    "", SI);
966      }
967      new StoreInst(EltVal, DestField, SI);
968    }
969
970  } else {
971    const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
972    const Type *ArrayEltTy = ATy->getElementType();
973    uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
974    uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
975
976    uint64_t Shift;
977
978    if (TD->isBigEndian())
979      Shift = AllocaSizeBits-ElementOffset;
980    else
981      Shift = 0;
982
983    for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
984      // Ignore zero sized fields like {}, they obviously contain no data.
985      if (ElementSizeBits == 0) continue;
986
987      Value *EltVal = SrcVal;
988      if (Shift) {
989        Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
990        EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
991                                            "sroa.store.elt", SI);
992      }
993
994      // Truncate down to an integer of the right size.
995      if (ElementSizeBits != AllocaSizeBits)
996        EltVal = new TruncInst(EltVal,
997                               IntegerType::get(SI->getContext(),
998                                                ElementSizeBits),"",SI);
999      Value *DestField = NewElts[i];
1000      if (EltVal->getType() == ArrayEltTy) {
1001        // Storing to an integer field of this size, just do it.
1002      } else if (ArrayEltTy->isFloatingPoint() || isa<VectorType>(ArrayEltTy)) {
1003        // Bitcast to the right element type (for fp/vector values).
1004        EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
1005      } else {
1006        // Otherwise, bitcast the dest pointer (for aggregates).
1007        DestField = new BitCastInst(DestField,
1008                              PointerType::getUnqual(EltVal->getType()),
1009                                    "", SI);
1010      }
1011      new StoreInst(EltVal, DestField, SI);
1012
1013      if (TD->isBigEndian())
1014        Shift -= ElementOffset;
1015      else
1016        Shift += ElementOffset;
1017    }
1018  }
1019
1020  DeadInsts.push_back(SI);
1021}
1022
1023/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
1024/// an integer.  Load the individual pieces to form the aggregate value.
1025void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
1026                                        SmallVector<AllocaInst*, 32> &NewElts) {
1027  // Extract each element out of the NewElts according to its structure offset
1028  // and form the result value.
1029  const Type *AllocaEltTy = AI->getAllocatedType();
1030  uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
1031
1032  DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
1033               << '\n');
1034
1035  // There are two forms here: AI could be an array or struct.  Both cases
1036  // have different ways to compute the element offset.
1037  const StructLayout *Layout = 0;
1038  uint64_t ArrayEltBitOffset = 0;
1039  if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1040    Layout = TD->getStructLayout(EltSTy);
1041  } else {
1042    const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
1043    ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
1044  }
1045
1046  Value *ResultVal =
1047    Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
1048
1049  for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1050    // Load the value from the alloca.  If the NewElt is an aggregate, cast
1051    // the pointer to an integer of the same size before doing the load.
1052    Value *SrcField = NewElts[i];
1053    const Type *FieldTy =
1054      cast<PointerType>(SrcField->getType())->getElementType();
1055    uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1056
1057    // Ignore zero sized fields like {}, they obviously contain no data.
1058    if (FieldSizeBits == 0) continue;
1059
1060    const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
1061                                                     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  DeadInsts.push_back(LI);
1103}
1104
1105/// HasPadding - Return true if the specified type has any structure or
1106/// alignment padding, false otherwise.
1107static bool HasPadding(const Type *Ty, const TargetData &TD) {
1108  if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1109    const StructLayout *SL = TD.getStructLayout(STy);
1110    unsigned PrevFieldBitOffset = 0;
1111    for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1112      unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1113
1114      // Padding in sub-elements?
1115      if (HasPadding(STy->getElementType(i), TD))
1116        return true;
1117
1118      // Check to see if there is any padding between this element and the
1119      // previous one.
1120      if (i) {
1121        unsigned PrevFieldEnd =
1122        PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1123        if (PrevFieldEnd < FieldBitOffset)
1124          return true;
1125      }
1126
1127      PrevFieldBitOffset = FieldBitOffset;
1128    }
1129
1130    //  Check for tail padding.
1131    if (unsigned EltCount = STy->getNumElements()) {
1132      unsigned PrevFieldEnd = PrevFieldBitOffset +
1133                   TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
1134      if (PrevFieldEnd < SL->getSizeInBits())
1135        return true;
1136    }
1137
1138  } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1139    return HasPadding(ATy->getElementType(), TD);
1140  } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1141    return HasPadding(VTy->getElementType(), TD);
1142  }
1143  return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
1144}
1145
1146/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1147/// an aggregate can be broken down into elements.  Return 0 if not, 3 if safe,
1148/// or 1 if safe after canonicalization has been performed.
1149int SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
1150  // Loop over the use list of the alloca.  We can only transform it if all of
1151  // the users are safe to transform.
1152  AllocaInfo Info;
1153
1154  isSafeForScalarRepl(AI, AI, 0, Info);
1155  if (Info.isUnsafe) {
1156    DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
1157    return 0;
1158  }
1159
1160  // Okay, we know all the users are promotable.  If the aggregate is a memcpy
1161  // source and destination, we have to be careful.  In particular, the memcpy
1162  // could be moving around elements that live in structure padding of the LLVM
1163  // types, but may actually be used.  In these cases, we refuse to promote the
1164  // struct.
1165  if (Info.isMemCpySrc && Info.isMemCpyDst &&
1166      HasPadding(AI->getAllocatedType(), *TD))
1167    return 0;
1168
1169  // If we require cleanup, return 1, otherwise return 3.
1170  return Info.needsCleanup ? 1 : 3;
1171}
1172
1173/// CleanupAllocaUsers - If SROA reported that it can promote the specified
1174/// allocation, but only if cleaned up, perform the cleanups required.
1175void SROA::CleanupAllocaUsers(Value *V) {
1176  for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
1177       UI != E; ) {
1178    User *U = *UI++;
1179    Instruction *I = cast<Instruction>(U);
1180    SmallVector<DbgInfoIntrinsic *, 2> DbgInUses;
1181    if (!isa<StoreInst>(I) && OnlyUsedByDbgInfoIntrinsics(I, &DbgInUses)) {
1182      // Safe to remove debug info uses.
1183      while (!DbgInUses.empty()) {
1184        DbgInfoIntrinsic *DI = DbgInUses.pop_back_val();
1185        DI->eraseFromParent();
1186      }
1187      I->eraseFromParent();
1188    }
1189  }
1190}
1191
1192/// MergeInType - Add the 'In' type to the accumulated type (Accum) so far at
1193/// the offset specified by Offset (which is specified in bytes).
1194///
1195/// There are two cases we handle here:
1196///   1) A union of vector types of the same size and potentially its elements.
1197///      Here we turn element accesses into insert/extract element operations.
1198///      This promotes a <4 x float> with a store of float to the third element
1199///      into a <4 x float> that uses insert element.
1200///   2) A fully general blob of memory, which we turn into some (potentially
1201///      large) integer type with extract and insert operations where the loads
1202///      and stores would mutate the memory.
1203static void MergeInType(const Type *In, uint64_t Offset, const Type *&VecTy,
1204                        unsigned AllocaSize, const TargetData &TD,
1205                        LLVMContext &Context) {
1206  // If this could be contributing to a vector, analyze it.
1207  if (VecTy != Type::getVoidTy(Context)) { // either null or a vector type.
1208
1209    // If the In type is a vector that is the same size as the alloca, see if it
1210    // matches the existing VecTy.
1211    if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
1212      if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
1213        // If we're storing/loading a vector of the right size, allow it as a
1214        // vector.  If this the first vector we see, remember the type so that
1215        // we know the element size.
1216        if (VecTy == 0)
1217          VecTy = VInTy;
1218        return;
1219      }
1220    } else if (In->isFloatTy() || In->isDoubleTy() ||
1221               (isa<IntegerType>(In) && In->getPrimitiveSizeInBits() >= 8 &&
1222                isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
1223      // If we're accessing something that could be an element of a vector, see
1224      // if the implied vector agrees with what we already have and if Offset is
1225      // compatible with it.
1226      unsigned EltSize = In->getPrimitiveSizeInBits()/8;
1227      if (Offset % EltSize == 0 &&
1228          AllocaSize % EltSize == 0 &&
1229          (VecTy == 0 ||
1230           cast<VectorType>(VecTy)->getElementType()
1231                 ->getPrimitiveSizeInBits()/8 == EltSize)) {
1232        if (VecTy == 0)
1233          VecTy = VectorType::get(In, AllocaSize/EltSize);
1234        return;
1235      }
1236    }
1237  }
1238
1239  // Otherwise, we have a case that we can't handle with an optimized vector
1240  // form.  We can still turn this into a large integer.
1241  VecTy = Type::getVoidTy(Context);
1242}
1243
1244/// CanConvertToScalar - V is a pointer.  If we can convert the pointee and all
1245/// its accesses to a single vector type, return true and set VecTy to
1246/// the new type.  If we could convert the alloca into a single promotable
1247/// integer, return true but set VecTy to VoidTy.  Further, if the use is not a
1248/// completely trivial use that mem2reg could promote, set IsNotTrivial.  Offset
1249/// is the current offset from the base of the alloca being analyzed.
1250///
1251/// If we see at least one access to the value that is as a vector type, set the
1252/// SawVec flag.
1253bool SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
1254                              bool &SawVec, uint64_t Offset,
1255                              unsigned AllocaSize) {
1256  for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1257    Instruction *User = cast<Instruction>(*UI);
1258
1259    if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1260      // Don't break volatile loads.
1261      if (LI->isVolatile())
1262        return false;
1263      MergeInType(LI->getType(), Offset, VecTy,
1264                  AllocaSize, *TD, V->getContext());
1265      SawVec |= isa<VectorType>(LI->getType());
1266      continue;
1267    }
1268
1269    if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1270      // Storing the pointer, not into the value?
1271      if (SI->getOperand(0) == V || SI->isVolatile()) return 0;
1272      MergeInType(SI->getOperand(0)->getType(), Offset,
1273                  VecTy, AllocaSize, *TD, V->getContext());
1274      SawVec |= isa<VectorType>(SI->getOperand(0)->getType());
1275      continue;
1276    }
1277
1278    if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
1279      if (!CanConvertToScalar(BCI, IsNotTrivial, VecTy, SawVec, Offset,
1280                              AllocaSize))
1281        return false;
1282      IsNotTrivial = true;
1283      continue;
1284    }
1285
1286    if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1287      // If this is a GEP with a variable indices, we can't handle it.
1288      if (!GEP->hasAllConstantIndices())
1289        return false;
1290
1291      // Compute the offset that this GEP adds to the pointer.
1292      SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1293      uint64_t GEPOffset = TD->getIndexedOffset(GEP->getPointerOperandType(),
1294                                                &Indices[0], Indices.size());
1295      // See if all uses can be converted.
1296      if (!CanConvertToScalar(GEP, IsNotTrivial, VecTy, SawVec,Offset+GEPOffset,
1297                              AllocaSize))
1298        return false;
1299      IsNotTrivial = true;
1300      continue;
1301    }
1302
1303    // If this is a constant sized memset of a constant value (e.g. 0) we can
1304    // handle it.
1305    if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1306      // Store of constant value and constant size.
1307      if (isa<ConstantInt>(MSI->getValue()) &&
1308          isa<ConstantInt>(MSI->getLength())) {
1309        IsNotTrivial = true;
1310        continue;
1311      }
1312    }
1313
1314    // If this is a memcpy or memmove into or out of the whole allocation, we
1315    // can handle it like a load or store of the scalar type.
1316    if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1317      if (ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength()))
1318        if (Len->getZExtValue() == AllocaSize && Offset == 0) {
1319          IsNotTrivial = true;
1320          continue;
1321        }
1322    }
1323
1324    // Ignore dbg intrinsic.
1325    if (isa<DbgInfoIntrinsic>(User))
1326      continue;
1327
1328    // Otherwise, we cannot handle this!
1329    return false;
1330  }
1331
1332  return true;
1333}
1334
1335/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
1336/// directly.  This happens when we are converting an "integer union" to a
1337/// single integer scalar, or when we are converting a "vector union" to a
1338/// vector with insert/extractelement instructions.
1339///
1340/// Offset is an offset from the original alloca, in bits that need to be
1341/// shifted to the right.  By the end of this, there should be no uses of Ptr.
1342void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset) {
1343  while (!Ptr->use_empty()) {
1344    Instruction *User = cast<Instruction>(Ptr->use_back());
1345
1346    if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
1347      ConvertUsesToScalar(CI, NewAI, Offset);
1348      CI->eraseFromParent();
1349      continue;
1350    }
1351
1352    if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1353      // Compute the offset that this GEP adds to the pointer.
1354      SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1355      uint64_t GEPOffset = TD->getIndexedOffset(GEP->getPointerOperandType(),
1356                                                &Indices[0], Indices.size());
1357      ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
1358      GEP->eraseFromParent();
1359      continue;
1360    }
1361
1362    IRBuilder<> Builder(User->getParent(), User);
1363
1364    if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1365      // The load is a bit extract from NewAI shifted right by Offset bits.
1366      Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
1367      Value *NewLoadVal
1368        = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
1369      LI->replaceAllUsesWith(NewLoadVal);
1370      LI->eraseFromParent();
1371      continue;
1372    }
1373
1374    if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1375      assert(SI->getOperand(0) != Ptr && "Consistency error!");
1376      Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
1377      Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
1378                                             Builder);
1379      Builder.CreateStore(New, NewAI);
1380      SI->eraseFromParent();
1381
1382      // If the load we just inserted is now dead, then the inserted store
1383      // overwrote the entire thing.
1384      if (Old->use_empty())
1385        Old->eraseFromParent();
1386      continue;
1387    }
1388
1389    // If this is a constant sized memset of a constant value (e.g. 0) we can
1390    // transform it into a store of the expanded constant value.
1391    if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1392      assert(MSI->getRawDest() == Ptr && "Consistency error!");
1393      unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
1394      if (NumBytes != 0) {
1395        unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
1396
1397        // Compute the value replicated the right number of times.
1398        APInt APVal(NumBytes*8, Val);
1399
1400        // Splat the value if non-zero.
1401        if (Val)
1402          for (unsigned i = 1; i != NumBytes; ++i)
1403            APVal |= APVal << 8;
1404
1405        Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
1406        Value *New = ConvertScalar_InsertValue(
1407                                    ConstantInt::get(User->getContext(), APVal),
1408                                               Old, Offset, Builder);
1409        Builder.CreateStore(New, NewAI);
1410
1411        // If the load we just inserted is now dead, then the memset overwrote
1412        // the entire thing.
1413        if (Old->use_empty())
1414          Old->eraseFromParent();
1415      }
1416      MSI->eraseFromParent();
1417      continue;
1418    }
1419
1420    // If this is a memcpy or memmove into or out of the whole allocation, we
1421    // can handle it like a load or store of the scalar type.
1422    if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1423      assert(Offset == 0 && "must be store to start of alloca");
1424
1425      // If the source and destination are both to the same alloca, then this is
1426      // a noop copy-to-self, just delete it.  Otherwise, emit a load and store
1427      // as appropriate.
1428      AllocaInst *OrigAI = cast<AllocaInst>(Ptr->getUnderlyingObject());
1429
1430      if (MTI->getSource()->getUnderlyingObject() != OrigAI) {
1431        // Dest must be OrigAI, change this to be a load from the original
1432        // pointer (bitcasted), then a store to our new alloca.
1433        assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
1434        Value *SrcPtr = MTI->getSource();
1435        SrcPtr = Builder.CreateBitCast(SrcPtr, NewAI->getType());
1436
1437        LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
1438        SrcVal->setAlignment(MTI->getAlignment());
1439        Builder.CreateStore(SrcVal, NewAI);
1440      } else if (MTI->getDest()->getUnderlyingObject() != OrigAI) {
1441        // Src must be OrigAI, change this to be a load from NewAI then a store
1442        // through the original dest pointer (bitcasted).
1443        assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
1444        LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
1445
1446        Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), NewAI->getType());
1447        StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
1448        NewStore->setAlignment(MTI->getAlignment());
1449      } else {
1450        // Noop transfer. Src == Dst
1451      }
1452
1453
1454      MTI->eraseFromParent();
1455      continue;
1456    }
1457
1458    // If user is a dbg info intrinsic then it is safe to remove it.
1459    if (isa<DbgInfoIntrinsic>(User)) {
1460      User->eraseFromParent();
1461      continue;
1462    }
1463
1464    llvm_unreachable("Unsupported operation!");
1465  }
1466}
1467
1468/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
1469/// or vector value FromVal, extracting the bits from the offset specified by
1470/// Offset.  This returns the value, which is of type ToType.
1471///
1472/// This happens when we are converting an "integer union" to a single
1473/// integer scalar, or when we are converting a "vector union" to a vector with
1474/// insert/extractelement instructions.
1475///
1476/// Offset is an offset from the original alloca, in bits that need to be
1477/// shifted to the right.
1478Value *SROA::ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
1479                                        uint64_t Offset, IRBuilder<> &Builder) {
1480  // If the load is of the whole new alloca, no conversion is needed.
1481  if (FromVal->getType() == ToType && Offset == 0)
1482    return FromVal;
1483
1484  // If the result alloca is a vector type, this is either an element
1485  // access or a bitcast to another vector type of the same size.
1486  if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
1487    if (isa<VectorType>(ToType))
1488      return Builder.CreateBitCast(FromVal, ToType, "tmp");
1489
1490    // Otherwise it must be an element access.
1491    unsigned Elt = 0;
1492    if (Offset) {
1493      unsigned EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
1494      Elt = Offset/EltSize;
1495      assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
1496    }
1497    // Return the element extracted out of it.
1498    Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
1499                    Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
1500    if (V->getType() != ToType)
1501      V = Builder.CreateBitCast(V, ToType, "tmp");
1502    return V;
1503  }
1504
1505  // If ToType is a first class aggregate, extract out each of the pieces and
1506  // use insertvalue's to form the FCA.
1507  if (const StructType *ST = dyn_cast<StructType>(ToType)) {
1508    const StructLayout &Layout = *TD->getStructLayout(ST);
1509    Value *Res = UndefValue::get(ST);
1510    for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1511      Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
1512                                        Offset+Layout.getElementOffsetInBits(i),
1513                                              Builder);
1514      Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1515    }
1516    return Res;
1517  }
1518
1519  if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
1520    uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
1521    Value *Res = UndefValue::get(AT);
1522    for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1523      Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
1524                                              Offset+i*EltSize, Builder);
1525      Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1526    }
1527    return Res;
1528  }
1529
1530  // Otherwise, this must be a union that was converted to an integer value.
1531  const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
1532
1533  // If this is a big-endian system and the load is narrower than the
1534  // full alloca type, we need to do a shift to get the right bits.
1535  int ShAmt = 0;
1536  if (TD->isBigEndian()) {
1537    // On big-endian machines, the lowest bit is stored at the bit offset
1538    // from the pointer given by getTypeStoreSizeInBits.  This matters for
1539    // integers with a bitwidth that is not a multiple of 8.
1540    ShAmt = TD->getTypeStoreSizeInBits(NTy) -
1541            TD->getTypeStoreSizeInBits(ToType) - Offset;
1542  } else {
1543    ShAmt = Offset;
1544  }
1545
1546  // Note: we support negative bitwidths (with shl) which are not defined.
1547  // We do this to support (f.e.) loads off the end of a structure where
1548  // only some bits are used.
1549  if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
1550    FromVal = Builder.CreateLShr(FromVal,
1551                                 ConstantInt::get(FromVal->getType(),
1552                                                           ShAmt), "tmp");
1553  else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
1554    FromVal = Builder.CreateShl(FromVal,
1555                                ConstantInt::get(FromVal->getType(),
1556                                                          -ShAmt), "tmp");
1557
1558  // Finally, unconditionally truncate the integer to the right width.
1559  unsigned LIBitWidth = TD->getTypeSizeInBits(ToType);
1560  if (LIBitWidth < NTy->getBitWidth())
1561    FromVal =
1562      Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
1563                                                    LIBitWidth), "tmp");
1564  else if (LIBitWidth > NTy->getBitWidth())
1565    FromVal =
1566       Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
1567                                                    LIBitWidth), "tmp");
1568
1569  // If the result is an integer, this is a trunc or bitcast.
1570  if (isa<IntegerType>(ToType)) {
1571    // Should be done.
1572  } else if (ToType->isFloatingPoint() || isa<VectorType>(ToType)) {
1573    // Just do a bitcast, we know the sizes match up.
1574    FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
1575  } else {
1576    // Otherwise must be a pointer.
1577    FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
1578  }
1579  assert(FromVal->getType() == ToType && "Didn't convert right?");
1580  return FromVal;
1581}
1582
1583/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
1584/// or vector value "Old" at the offset specified by Offset.
1585///
1586/// This happens when we are converting an "integer union" to a
1587/// single integer scalar, or when we are converting a "vector union" to a
1588/// vector with insert/extractelement instructions.
1589///
1590/// Offset is an offset from the original alloca, in bits that need to be
1591/// shifted to the right.
1592Value *SROA::ConvertScalar_InsertValue(Value *SV, Value *Old,
1593                                       uint64_t Offset, IRBuilder<> &Builder) {
1594
1595  // Convert the stored type to the actual type, shift it left to insert
1596  // then 'or' into place.
1597  const Type *AllocaType = Old->getType();
1598  LLVMContext &Context = Old->getContext();
1599
1600  if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
1601    uint64_t VecSize = TD->getTypeAllocSizeInBits(VTy);
1602    uint64_t ValSize = TD->getTypeAllocSizeInBits(SV->getType());
1603
1604    // Changing the whole vector with memset or with an access of a different
1605    // vector type?
1606    if (ValSize == VecSize)
1607      return Builder.CreateBitCast(SV, AllocaType, "tmp");
1608
1609    uint64_t EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
1610
1611    // Must be an element insertion.
1612    unsigned Elt = Offset/EltSize;
1613
1614    if (SV->getType() != VTy->getElementType())
1615      SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
1616
1617    SV = Builder.CreateInsertElement(Old, SV,
1618                     ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
1619                                     "tmp");
1620    return SV;
1621  }
1622
1623  // If SV is a first-class aggregate value, insert each value recursively.
1624  if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
1625    const StructLayout &Layout = *TD->getStructLayout(ST);
1626    for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1627      Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1628      Old = ConvertScalar_InsertValue(Elt, Old,
1629                                      Offset+Layout.getElementOffsetInBits(i),
1630                                      Builder);
1631    }
1632    return Old;
1633  }
1634
1635  if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
1636    uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
1637    for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1638      Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1639      Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
1640    }
1641    return Old;
1642  }
1643
1644  // If SV is a float, convert it to the appropriate integer type.
1645  // If it is a pointer, do the same.
1646  unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1647  unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1648  unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1649  unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
1650  if (SV->getType()->isFloatingPoint() || isa<VectorType>(SV->getType()))
1651    SV = Builder.CreateBitCast(SV,
1652                            IntegerType::get(SV->getContext(),SrcWidth), "tmp");
1653  else if (isa<PointerType>(SV->getType()))
1654    SV = Builder.CreatePtrToInt(SV, TD->getIntPtrType(SV->getContext()), "tmp");
1655
1656  // Zero extend or truncate the value if needed.
1657  if (SV->getType() != AllocaType) {
1658    if (SV->getType()->getPrimitiveSizeInBits() <
1659             AllocaType->getPrimitiveSizeInBits())
1660      SV = Builder.CreateZExt(SV, AllocaType, "tmp");
1661    else {
1662      // Truncation may be needed if storing more than the alloca can hold
1663      // (undefined behavior).
1664      SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
1665      SrcWidth = DestWidth;
1666      SrcStoreWidth = DestStoreWidth;
1667    }
1668  }
1669
1670  // If this is a big-endian system and the store is narrower than the
1671  // full alloca type, we need to do a shift to get the right bits.
1672  int ShAmt = 0;
1673  if (TD->isBigEndian()) {
1674    // On big-endian machines, the lowest bit is stored at the bit offset
1675    // from the pointer given by getTypeStoreSizeInBits.  This matters for
1676    // integers with a bitwidth that is not a multiple of 8.
1677    ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
1678  } else {
1679    ShAmt = Offset;
1680  }
1681
1682  // Note: we support negative bitwidths (with shr) which are not defined.
1683  // We do this to support (f.e.) stores off the end of a structure where
1684  // only some bits in the structure are set.
1685  APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1686  if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1687    SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
1688                           ShAmt), "tmp");
1689    Mask <<= ShAmt;
1690  } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1691    SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
1692                            -ShAmt), "tmp");
1693    Mask = Mask.lshr(-ShAmt);
1694  }
1695
1696  // Mask out the bits we are about to insert from the old value, and or
1697  // in the new bits.
1698  if (SrcWidth != DestWidth) {
1699    assert(DestWidth > SrcWidth);
1700    Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
1701    SV = Builder.CreateOr(Old, SV, "ins");
1702  }
1703  return SV;
1704}
1705
1706
1707
1708/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1709/// some part of a constant global variable.  This intentionally only accepts
1710/// constant expressions because we don't can't rewrite arbitrary instructions.
1711static bool PointsToConstantGlobal(Value *V) {
1712  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1713    return GV->isConstant();
1714  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1715    if (CE->getOpcode() == Instruction::BitCast ||
1716        CE->getOpcode() == Instruction::GetElementPtr)
1717      return PointsToConstantGlobal(CE->getOperand(0));
1718  return false;
1719}
1720
1721/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1722/// pointer to an alloca.  Ignore any reads of the pointer, return false if we
1723/// see any stores or other unknown uses.  If we see pointer arithmetic, keep
1724/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1725/// the uses.  If we see a memcpy/memmove that targets an unoffseted pointer to
1726/// the alloca, and if the source pointer is a pointer to a constant  global, we
1727/// can optimize this.
1728static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1729                                           bool isOffset) {
1730  for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1731    if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
1732      // Ignore non-volatile loads, they are always ok.
1733      if (!LI->isVolatile())
1734        continue;
1735
1736    if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1737      // If uses of the bitcast are ok, we are ok.
1738      if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1739        return false;
1740      continue;
1741    }
1742    if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1743      // If the GEP has all zero indices, it doesn't offset the pointer.  If it
1744      // doesn't, it does.
1745      if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1746                                         isOffset || !GEP->hasAllZeroIndices()))
1747        return false;
1748      continue;
1749    }
1750
1751    // If this is isn't our memcpy/memmove, reject it as something we can't
1752    // handle.
1753    if (!isa<MemTransferInst>(*UI))
1754      return false;
1755
1756    // If we already have seen a copy, reject the second one.
1757    if (TheCopy) return false;
1758
1759    // If the pointer has been offset from the start of the alloca, we can't
1760    // safely handle this.
1761    if (isOffset) return false;
1762
1763    // If the memintrinsic isn't using the alloca as the dest, reject it.
1764    if (UI.getOperandNo() != 1) return false;
1765
1766    MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1767
1768    // If the source of the memcpy/move is not a constant global, reject it.
1769    if (!PointsToConstantGlobal(MI->getOperand(2)))
1770      return false;
1771
1772    // Otherwise, the transform is safe.  Remember the copy instruction.
1773    TheCopy = MI;
1774  }
1775  return true;
1776}
1777
1778/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1779/// modified by a copy from a constant global.  If we can prove this, we can
1780/// replace any uses of the alloca with uses of the global directly.
1781Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
1782  Instruction *TheCopy = 0;
1783  if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1784    return TheCopy;
1785  return 0;
1786}
1787