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