ScalarReplAggregates.cpp revision 125ef76934f37e3fdc8ce4a2cc238850d06c5912
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/Module.h"
32#include "llvm/Pass.h"
33#include "llvm/Analysis/DebugInfo.h"
34#include "llvm/Analysis/DIBuilder.h"
35#include "llvm/Analysis/Dominators.h"
36#include "llvm/Analysis/Loads.h"
37#include "llvm/Analysis/ValueTracking.h"
38#include "llvm/Target/TargetData.h"
39#include "llvm/Transforms/Utils/PromoteMemToReg.h"
40#include "llvm/Transforms/Utils/Local.h"
41#include "llvm/Transforms/Utils/SSAUpdater.h"
42#include "llvm/Support/CallSite.h"
43#include "llvm/Support/Debug.h"
44#include "llvm/Support/ErrorHandling.h"
45#include "llvm/Support/GetElementPtrTypeIterator.h"
46#include "llvm/Support/IRBuilder.h"
47#include "llvm/Support/MathExtras.h"
48#include "llvm/Support/raw_ostream.h"
49#include "llvm/ADT/SetVector.h"
50#include "llvm/ADT/SmallVector.h"
51#include "llvm/ADT/Statistic.h"
52using namespace llvm;
53
54STATISTIC(NumReplaced,  "Number of allocas broken up");
55STATISTIC(NumPromoted,  "Number of allocas promoted");
56STATISTIC(NumAdjusted,  "Number of scalar allocas adjusted to allow promotion");
57STATISTIC(NumConverted, "Number of aggregates converted to scalar");
58STATISTIC(NumGlobals,   "Number of allocas copied from constant global");
59
60namespace {
61  struct SROA : public FunctionPass {
62    SROA(int T, bool hasDT, char &ID)
63      : FunctionPass(ID), HasDomTree(hasDT) {
64      if (T == -1)
65        SRThreshold = 128;
66      else
67        SRThreshold = T;
68    }
69
70    bool runOnFunction(Function &F);
71
72    bool performScalarRepl(Function &F);
73    bool performPromotion(Function &F);
74
75  private:
76    bool HasDomTree;
77    TargetData *TD;
78
79    /// DeadInsts - Keep track of instructions we have made dead, so that
80    /// we can remove them after we are done working.
81    SmallVector<Value*, 32> DeadInsts;
82
83    /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
84    /// information about the uses.  All these fields are initialized to false
85    /// and set to true when something is learned.
86    struct AllocaInfo {
87      /// The alloca to promote.
88      AllocaInst *AI;
89
90      /// CheckedPHIs - This is a set of verified PHI nodes, to prevent infinite
91      /// looping and avoid redundant work.
92      SmallPtrSet<PHINode*, 8> CheckedPHIs;
93
94      /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
95      bool isUnsafe : 1;
96
97      /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
98      bool isMemCpySrc : 1;
99
100      /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
101      bool isMemCpyDst : 1;
102
103      /// hasSubelementAccess - This is true if a subelement of the alloca is
104      /// ever accessed, or false if the alloca is only accessed with mem
105      /// intrinsics or load/store that only access the entire alloca at once.
106      bool hasSubelementAccess : 1;
107
108      /// hasALoadOrStore - This is true if there are any loads or stores to it.
109      /// The alloca may just be accessed with memcpy, for example, which would
110      /// not set this.
111      bool hasALoadOrStore : 1;
112
113      explicit AllocaInfo(AllocaInst *ai)
114        : AI(ai), isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
115          hasSubelementAccess(false), hasALoadOrStore(false) {}
116    };
117
118    unsigned SRThreshold;
119
120    void MarkUnsafe(AllocaInfo &I, Instruction *User) {
121      I.isUnsafe = true;
122      DEBUG(dbgs() << "  Transformation preventing inst: " << *User << '\n');
123    }
124
125    bool isSafeAllocaToScalarRepl(AllocaInst *AI);
126
127    void isSafeForScalarRepl(Instruction *I, uint64_t Offset, AllocaInfo &Info);
128    void isSafePHISelectUseForScalarRepl(Instruction *User, uint64_t Offset,
129                                         AllocaInfo &Info);
130    void isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset, AllocaInfo &Info);
131    void isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
132                         Type *MemOpType, bool isStore, AllocaInfo &Info,
133                         Instruction *TheAccess, bool AllowWholeAccess);
134    bool TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size);
135    uint64_t FindElementAndOffset(Type *&T, uint64_t &Offset,
136                                  Type *&IdxTy);
137
138    void DoScalarReplacement(AllocaInst *AI,
139                             std::vector<AllocaInst*> &WorkList);
140    void DeleteDeadInstructions();
141
142    void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
143                              SmallVector<AllocaInst*, 32> &NewElts);
144    void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
145                        SmallVector<AllocaInst*, 32> &NewElts);
146    void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
147                    SmallVector<AllocaInst*, 32> &NewElts);
148    void RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
149                                  uint64_t Offset,
150                                  SmallVector<AllocaInst*, 32> &NewElts);
151    void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
152                                      AllocaInst *AI,
153                                      SmallVector<AllocaInst*, 32> &NewElts);
154    void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
155                                       SmallVector<AllocaInst*, 32> &NewElts);
156    void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
157                                      SmallVector<AllocaInst*, 32> &NewElts);
158
159    static MemTransferInst *isOnlyCopiedFromConstantGlobal(
160        AllocaInst *AI, SmallVector<Instruction*, 4> &ToDelete);
161  };
162
163  // SROA_DT - SROA that uses DominatorTree.
164  struct SROA_DT : public SROA {
165    static char ID;
166  public:
167    SROA_DT(int T = -1) : SROA(T, true, ID) {
168      initializeSROA_DTPass(*PassRegistry::getPassRegistry());
169    }
170
171    // getAnalysisUsage - This pass does not require any passes, but we know it
172    // will not alter the CFG, so say so.
173    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
174      AU.addRequired<DominatorTree>();
175      AU.setPreservesCFG();
176    }
177  };
178
179  // SROA_SSAUp - SROA that uses SSAUpdater.
180  struct SROA_SSAUp : public SROA {
181    static char ID;
182  public:
183    SROA_SSAUp(int T = -1) : SROA(T, false, ID) {
184      initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
185    }
186
187    // getAnalysisUsage - This pass does not require any passes, but we know it
188    // will not alter the CFG, so say so.
189    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
190      AU.setPreservesCFG();
191    }
192  };
193
194}
195
196char SROA_DT::ID = 0;
197char SROA_SSAUp::ID = 0;
198
199INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl",
200                "Scalar Replacement of Aggregates (DT)", false, false)
201INITIALIZE_PASS_DEPENDENCY(DominatorTree)
202INITIALIZE_PASS_END(SROA_DT, "scalarrepl",
203                "Scalar Replacement of Aggregates (DT)", false, false)
204
205INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
206                      "Scalar Replacement of Aggregates (SSAUp)", false, false)
207INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
208                    "Scalar Replacement of Aggregates (SSAUp)", false, false)
209
210// Public interface to the ScalarReplAggregates pass
211FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
212                                                   bool UseDomTree) {
213  if (UseDomTree)
214    return new SROA_DT(Threshold);
215  return new SROA_SSAUp(Threshold);
216}
217
218
219//===----------------------------------------------------------------------===//
220// Convert To Scalar Optimization.
221//===----------------------------------------------------------------------===//
222
223namespace {
224/// ConvertToScalarInfo - This class implements the "Convert To Scalar"
225/// optimization, which scans the uses of an alloca and determines if it can
226/// rewrite it in terms of a single new alloca that can be mem2reg'd.
227class ConvertToScalarInfo {
228  /// AllocaSize - The size of the alloca being considered in bytes.
229  unsigned AllocaSize;
230  const TargetData &TD;
231
232  /// IsNotTrivial - This is set to true if there is some access to the object
233  /// which means that mem2reg can't promote it.
234  bool IsNotTrivial;
235
236  /// ScalarKind - Tracks the kind of alloca being considered for promotion,
237  /// computed based on the uses of the alloca rather than the LLVM type system.
238  enum {
239    Unknown,
240
241    // Accesses via GEPs that are consistent with element access of a vector
242    // type. This will not be converted into a vector unless there is a later
243    // access using an actual vector type.
244    ImplicitVector,
245
246    // Accesses via vector operations and GEPs that are consistent with the
247    // layout of a vector type.
248    Vector,
249
250    // An integer bag-of-bits with bitwise operations for insertion and
251    // extraction. Any combination of types can be converted into this kind
252    // of scalar.
253    Integer
254  } ScalarKind;
255
256  /// VectorTy - This tracks the type that we should promote the vector to if
257  /// it is possible to turn it into a vector.  This starts out null, and if it
258  /// isn't possible to turn into a vector type, it gets set to VoidTy.
259  VectorType *VectorTy;
260
261  /// HadNonMemTransferAccess - True if there is at least one access to the
262  /// alloca that is not a MemTransferInst.  We don't want to turn structs into
263  /// large integers unless there is some potential for optimization.
264  bool HadNonMemTransferAccess;
265
266public:
267  explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
268    : AllocaSize(Size), TD(td), IsNotTrivial(false), ScalarKind(Unknown),
269      VectorTy(0), HadNonMemTransferAccess(false) { }
270
271  AllocaInst *TryConvert(AllocaInst *AI);
272
273private:
274  bool CanConvertToScalar(Value *V, uint64_t Offset);
275  void MergeInTypeForLoadOrStore(Type *In, uint64_t Offset);
276  bool MergeInVectorType(VectorType *VInTy, uint64_t Offset);
277  void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
278
279  Value *ConvertScalar_ExtractValue(Value *NV, Type *ToType,
280                                    uint64_t Offset, IRBuilder<> &Builder);
281  Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
282                                   uint64_t Offset, IRBuilder<> &Builder);
283};
284} // end anonymous namespace.
285
286
287/// TryConvert - Analyze the specified alloca, and if it is safe to do so,
288/// rewrite it to be a new alloca which is mem2reg'able.  This returns the new
289/// alloca if possible or null if not.
290AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
291  // If we can't convert this scalar, or if mem2reg can trivially do it, bail
292  // out.
293  if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
294    return 0;
295
296  // If an alloca has only memset / memcpy uses, it may still have an Unknown
297  // ScalarKind. Treat it as an Integer below.
298  if (ScalarKind == Unknown)
299    ScalarKind = Integer;
300
301  if (ScalarKind == Vector && VectorTy->getBitWidth() != AllocaSize * 8)
302    ScalarKind = Integer;
303
304  // If we were able to find a vector type that can handle this with
305  // insert/extract elements, and if there was at least one use that had
306  // a vector type, promote this to a vector.  We don't want to promote
307  // random stuff that doesn't use vectors (e.g. <9 x double>) because then
308  // we just get a lot of insert/extracts.  If at least one vector is
309  // involved, then we probably really do have a union of vector/array.
310  Type *NewTy;
311  if (ScalarKind == Vector) {
312    assert(VectorTy && "Missing type for vector scalar.");
313    DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n  TYPE = "
314          << *VectorTy << '\n');
315    NewTy = VectorTy;  // Use the vector type.
316  } else {
317    unsigned BitWidth = AllocaSize * 8;
318    if ((ScalarKind == ImplicitVector || ScalarKind == Integer) &&
319        !HadNonMemTransferAccess && !TD.fitsInLegalInteger(BitWidth))
320      return 0;
321
322    DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
323    // Create and insert the integer alloca.
324    NewTy = IntegerType::get(AI->getContext(), BitWidth);
325  }
326  AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
327  ConvertUsesToScalar(AI, NewAI, 0);
328  return NewAI;
329}
330
331/// MergeInTypeForLoadOrStore - Add the 'In' type to the accumulated vector type
332/// (VectorTy) so far at the offset specified by Offset (which is specified in
333/// bytes).
334///
335/// There are two cases we handle here:
336///   1) A union of vector types of the same size and potentially its elements.
337///      Here we turn element accesses into insert/extract element operations.
338///      This promotes a <4 x float> with a store of float to the third element
339///      into a <4 x float> that uses insert element.
340///   2) A fully general blob of memory, which we turn into some (potentially
341///      large) integer type with extract and insert operations where the loads
342///      and stores would mutate the memory.  We mark this by setting VectorTy
343///      to VoidTy.
344void ConvertToScalarInfo::MergeInTypeForLoadOrStore(Type *In,
345                                                    uint64_t Offset) {
346  // If we already decided to turn this into a blob of integer memory, there is
347  // nothing to be done.
348  if (ScalarKind == Integer)
349    return;
350
351  // If this could be contributing to a vector, analyze it.
352
353  // If the In type is a vector that is the same size as the alloca, see if it
354  // matches the existing VecTy.
355  if (VectorType *VInTy = dyn_cast<VectorType>(In)) {
356    if (MergeInVectorType(VInTy, Offset))
357      return;
358  } else if (In->isFloatTy() || In->isDoubleTy() ||
359             (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
360              isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
361    // Full width accesses can be ignored, because they can always be turned
362    // into bitcasts.
363    unsigned EltSize = In->getPrimitiveSizeInBits()/8;
364    if (EltSize == AllocaSize)
365      return;
366
367    // If we're accessing something that could be an element of a vector, see
368    // if the implied vector agrees with what we already have and if Offset is
369    // compatible with it.
370    if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
371        (!VectorTy || EltSize == VectorTy->getElementType()
372                                         ->getPrimitiveSizeInBits()/8)) {
373      if (!VectorTy) {
374        ScalarKind = ImplicitVector;
375        VectorTy = VectorType::get(In, AllocaSize/EltSize);
376      }
377      return;
378    }
379  }
380
381  // Otherwise, we have a case that we can't handle with an optimized vector
382  // form.  We can still turn this into a large integer.
383  ScalarKind = Integer;
384}
385
386/// MergeInVectorType - Handles the vector case of MergeInTypeForLoadOrStore,
387/// returning true if the type was successfully merged and false otherwise.
388bool ConvertToScalarInfo::MergeInVectorType(VectorType *VInTy,
389                                            uint64_t Offset) {
390  if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
391    // If we're storing/loading a vector of the right size, allow it as a
392    // vector.  If this the first vector we see, remember the type so that
393    // we know the element size. If this is a subsequent access, ignore it
394    // even if it is a differing type but the same size. Worst case we can
395    // bitcast the resultant vectors.
396    if (!VectorTy)
397      VectorTy = VInTy;
398    ScalarKind = Vector;
399    return true;
400  }
401
402  return false;
403}
404
405/// CanConvertToScalar - V is a pointer.  If we can convert the pointee and all
406/// its accesses to a single vector type, return true and set VecTy to
407/// the new type.  If we could convert the alloca into a single promotable
408/// integer, return true but set VecTy to VoidTy.  Further, if the use is not a
409/// completely trivial use that mem2reg could promote, set IsNotTrivial.  Offset
410/// is the current offset from the base of the alloca being analyzed.
411///
412/// If we see at least one access to the value that is as a vector type, set the
413/// SawVec flag.
414bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
415  for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
416    Instruction *User = cast<Instruction>(*UI);
417
418    if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
419      // Don't break volatile loads.
420      if (!LI->isSimple())
421        return false;
422      // Don't touch MMX operations.
423      if (LI->getType()->isX86_MMXTy())
424        return false;
425      HadNonMemTransferAccess = true;
426      MergeInTypeForLoadOrStore(LI->getType(), Offset);
427      continue;
428    }
429
430    if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
431      // Storing the pointer, not into the value?
432      if (SI->getOperand(0) == V || !SI->isSimple()) return false;
433      // Don't touch MMX operations.
434      if (SI->getOperand(0)->getType()->isX86_MMXTy())
435        return false;
436      HadNonMemTransferAccess = true;
437      MergeInTypeForLoadOrStore(SI->getOperand(0)->getType(), Offset);
438      continue;
439    }
440
441    if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
442      if (!onlyUsedByLifetimeMarkers(BCI))
443        IsNotTrivial = true;  // Can't be mem2reg'd.
444      if (!CanConvertToScalar(BCI, Offset))
445        return false;
446      continue;
447    }
448
449    if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
450      // If this is a GEP with a variable indices, we can't handle it.
451      if (!GEP->hasAllConstantIndices())
452        return false;
453
454      // Compute the offset that this GEP adds to the pointer.
455      SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
456      if (!GEP->getPointerOperandType()->isPointerTy())
457        return false;
458      uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
459                                               Indices);
460      // See if all uses can be converted.
461      if (!CanConvertToScalar(GEP, Offset+GEPOffset))
462        return false;
463      IsNotTrivial = true;  // Can't be mem2reg'd.
464      HadNonMemTransferAccess = true;
465      continue;
466    }
467
468    // If this is a constant sized memset of a constant value (e.g. 0) we can
469    // handle it.
470    if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
471      // Store of constant value.
472      if (!isa<ConstantInt>(MSI->getValue()))
473        return false;
474
475      // Store of constant size.
476      ConstantInt *Len = dyn_cast<ConstantInt>(MSI->getLength());
477      if (!Len)
478        return false;
479
480      // If the size differs from the alloca, we can only convert the alloca to
481      // an integer bag-of-bits.
482      // FIXME: This should handle all of the cases that are currently accepted
483      // as vector element insertions.
484      if (Len->getZExtValue() != AllocaSize || Offset != 0)
485        ScalarKind = Integer;
486
487      IsNotTrivial = true;  // Can't be mem2reg'd.
488      HadNonMemTransferAccess = true;
489      continue;
490    }
491
492    // If this is a memcpy or memmove into or out of the whole allocation, we
493    // can handle it like a load or store of the scalar type.
494    if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
495      ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
496      if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
497        return false;
498
499      IsNotTrivial = true;  // Can't be mem2reg'd.
500      continue;
501    }
502
503    // If this is a lifetime intrinsic, we can handle it.
504    if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
505      if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
506          II->getIntrinsicID() == Intrinsic::lifetime_end) {
507        continue;
508      }
509    }
510
511    // Otherwise, we cannot handle this!
512    return false;
513  }
514
515  return true;
516}
517
518/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
519/// directly.  This happens when we are converting an "integer union" to a
520/// single integer scalar, or when we are converting a "vector union" to a
521/// vector with insert/extractelement instructions.
522///
523/// Offset is an offset from the original alloca, in bits that need to be
524/// shifted to the right.  By the end of this, there should be no uses of Ptr.
525void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
526                                              uint64_t Offset) {
527  while (!Ptr->use_empty()) {
528    Instruction *User = cast<Instruction>(Ptr->use_back());
529
530    if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
531      ConvertUsesToScalar(CI, NewAI, Offset);
532      CI->eraseFromParent();
533      continue;
534    }
535
536    if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
537      // Compute the offset that this GEP adds to the pointer.
538      SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
539      uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
540                                               Indices);
541      ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
542      GEP->eraseFromParent();
543      continue;
544    }
545
546    IRBuilder<> Builder(User);
547
548    if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
549      // The load is a bit extract from NewAI shifted right by Offset bits.
550      Value *LoadedVal = Builder.CreateLoad(NewAI);
551      Value *NewLoadVal
552        = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
553      LI->replaceAllUsesWith(NewLoadVal);
554      LI->eraseFromParent();
555      continue;
556    }
557
558    if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
559      assert(SI->getOperand(0) != Ptr && "Consistency error!");
560      Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
561      Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
562                                             Builder);
563      Builder.CreateStore(New, NewAI);
564      SI->eraseFromParent();
565
566      // If the load we just inserted is now dead, then the inserted store
567      // overwrote the entire thing.
568      if (Old->use_empty())
569        Old->eraseFromParent();
570      continue;
571    }
572
573    // If this is a constant sized memset of a constant value (e.g. 0) we can
574    // transform it into a store of the expanded constant value.
575    if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
576      assert(MSI->getRawDest() == Ptr && "Consistency error!");
577      unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
578      if (NumBytes != 0) {
579        unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
580
581        // Compute the value replicated the right number of times.
582        APInt APVal(NumBytes*8, Val);
583
584        // Splat the value if non-zero.
585        if (Val)
586          for (unsigned i = 1; i != NumBytes; ++i)
587            APVal |= APVal << 8;
588
589        Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
590        Value *New = ConvertScalar_InsertValue(
591                                    ConstantInt::get(User->getContext(), APVal),
592                                               Old, Offset, Builder);
593        Builder.CreateStore(New, NewAI);
594
595        // If the load we just inserted is now dead, then the memset overwrote
596        // the entire thing.
597        if (Old->use_empty())
598          Old->eraseFromParent();
599      }
600      MSI->eraseFromParent();
601      continue;
602    }
603
604    // If this is a memcpy or memmove into or out of the whole allocation, we
605    // can handle it like a load or store of the scalar type.
606    if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
607      assert(Offset == 0 && "must be store to start of alloca");
608
609      // If the source and destination are both to the same alloca, then this is
610      // a noop copy-to-self, just delete it.  Otherwise, emit a load and store
611      // as appropriate.
612      AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, &TD, 0));
613
614      if (GetUnderlyingObject(MTI->getSource(), &TD, 0) != OrigAI) {
615        // Dest must be OrigAI, change this to be a load from the original
616        // pointer (bitcasted), then a store to our new alloca.
617        assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
618        Value *SrcPtr = MTI->getSource();
619        PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
620        PointerType* AIPTy = cast<PointerType>(NewAI->getType());
621        if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
622          AIPTy = PointerType::get(AIPTy->getElementType(),
623                                   SPTy->getAddressSpace());
624        }
625        SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
626
627        LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
628        SrcVal->setAlignment(MTI->getAlignment());
629        Builder.CreateStore(SrcVal, NewAI);
630      } else if (GetUnderlyingObject(MTI->getDest(), &TD, 0) != OrigAI) {
631        // Src must be OrigAI, change this to be a load from NewAI then a store
632        // through the original dest pointer (bitcasted).
633        assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
634        LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
635
636        PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
637        PointerType* AIPTy = cast<PointerType>(NewAI->getType());
638        if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
639          AIPTy = PointerType::get(AIPTy->getElementType(),
640                                   DPTy->getAddressSpace());
641        }
642        Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
643
644        StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
645        NewStore->setAlignment(MTI->getAlignment());
646      } else {
647        // Noop transfer. Src == Dst
648      }
649
650      MTI->eraseFromParent();
651      continue;
652    }
653
654    if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
655      if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
656          II->getIntrinsicID() == Intrinsic::lifetime_end) {
657        // There's no need to preserve these, as the resulting alloca will be
658        // converted to a register anyways.
659        II->eraseFromParent();
660        continue;
661      }
662    }
663
664    llvm_unreachable("Unsupported operation!");
665  }
666}
667
668/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
669/// or vector value FromVal, extracting the bits from the offset specified by
670/// Offset.  This returns the value, which is of type ToType.
671///
672/// This happens when we are converting an "integer union" to a single
673/// integer scalar, or when we are converting a "vector union" to a vector with
674/// insert/extractelement instructions.
675///
676/// Offset is an offset from the original alloca, in bits that need to be
677/// shifted to the right.
678Value *ConvertToScalarInfo::
679ConvertScalar_ExtractValue(Value *FromVal, Type *ToType,
680                           uint64_t Offset, IRBuilder<> &Builder) {
681  // If the load is of the whole new alloca, no conversion is needed.
682  Type *FromType = FromVal->getType();
683  if (FromType == ToType && Offset == 0)
684    return FromVal;
685
686  // If the result alloca is a vector type, this is either an element
687  // access or a bitcast to another vector type of the same size.
688  if (VectorType *VTy = dyn_cast<VectorType>(FromType)) {
689    unsigned FromTypeSize = TD.getTypeAllocSize(FromType);
690    unsigned ToTypeSize = TD.getTypeAllocSize(ToType);
691    if (FromTypeSize == ToTypeSize)
692        return Builder.CreateBitCast(FromVal, ToType);
693
694    // Otherwise it must be an element access.
695    unsigned Elt = 0;
696    if (Offset) {
697      unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
698      Elt = Offset/EltSize;
699      assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
700    }
701    // Return the element extracted out of it.
702    Value *V = Builder.CreateExtractElement(FromVal, Builder.getInt32(Elt));
703    if (V->getType() != ToType)
704      V = Builder.CreateBitCast(V, ToType);
705    return V;
706  }
707
708  // If ToType is a first class aggregate, extract out each of the pieces and
709  // use insertvalue's to form the FCA.
710  if (StructType *ST = dyn_cast<StructType>(ToType)) {
711    const StructLayout &Layout = *TD.getStructLayout(ST);
712    Value *Res = UndefValue::get(ST);
713    for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
714      Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
715                                        Offset+Layout.getElementOffsetInBits(i),
716                                              Builder);
717      Res = Builder.CreateInsertValue(Res, Elt, i);
718    }
719    return Res;
720  }
721
722  if (ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
723    uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
724    Value *Res = UndefValue::get(AT);
725    for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
726      Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
727                                              Offset+i*EltSize, Builder);
728      Res = Builder.CreateInsertValue(Res, Elt, i);
729    }
730    return Res;
731  }
732
733  // Otherwise, this must be a union that was converted to an integer value.
734  IntegerType *NTy = cast<IntegerType>(FromVal->getType());
735
736  // If this is a big-endian system and the load is narrower than the
737  // full alloca type, we need to do a shift to get the right bits.
738  int ShAmt = 0;
739  if (TD.isBigEndian()) {
740    // On big-endian machines, the lowest bit is stored at the bit offset
741    // from the pointer given by getTypeStoreSizeInBits.  This matters for
742    // integers with a bitwidth that is not a multiple of 8.
743    ShAmt = TD.getTypeStoreSizeInBits(NTy) -
744            TD.getTypeStoreSizeInBits(ToType) - Offset;
745  } else {
746    ShAmt = Offset;
747  }
748
749  // Note: we support negative bitwidths (with shl) which are not defined.
750  // We do this to support (f.e.) loads off the end of a structure where
751  // only some bits are used.
752  if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
753    FromVal = Builder.CreateLShr(FromVal,
754                                 ConstantInt::get(FromVal->getType(), ShAmt));
755  else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
756    FromVal = Builder.CreateShl(FromVal,
757                                ConstantInt::get(FromVal->getType(), -ShAmt));
758
759  // Finally, unconditionally truncate the integer to the right width.
760  unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
761  if (LIBitWidth < NTy->getBitWidth())
762    FromVal =
763      Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
764                                                    LIBitWidth));
765  else if (LIBitWidth > NTy->getBitWidth())
766    FromVal =
767       Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
768                                                    LIBitWidth));
769
770  // If the result is an integer, this is a trunc or bitcast.
771  if (ToType->isIntegerTy()) {
772    // Should be done.
773  } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
774    // Just do a bitcast, we know the sizes match up.
775    FromVal = Builder.CreateBitCast(FromVal, ToType);
776  } else {
777    // Otherwise must be a pointer.
778    FromVal = Builder.CreateIntToPtr(FromVal, ToType);
779  }
780  assert(FromVal->getType() == ToType && "Didn't convert right?");
781  return FromVal;
782}
783
784/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
785/// or vector value "Old" at the offset specified by Offset.
786///
787/// This happens when we are converting an "integer union" to a
788/// single integer scalar, or when we are converting a "vector union" to a
789/// vector with insert/extractelement instructions.
790///
791/// Offset is an offset from the original alloca, in bits that need to be
792/// shifted to the right.
793Value *ConvertToScalarInfo::
794ConvertScalar_InsertValue(Value *SV, Value *Old,
795                          uint64_t Offset, IRBuilder<> &Builder) {
796  // Convert the stored type to the actual type, shift it left to insert
797  // then 'or' into place.
798  Type *AllocaType = Old->getType();
799  LLVMContext &Context = Old->getContext();
800
801  if (VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
802    uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
803    uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
804
805    // Changing the whole vector with memset or with an access of a different
806    // vector type?
807    if (ValSize == VecSize)
808        return Builder.CreateBitCast(SV, AllocaType);
809
810    // Must be an element insertion.
811    Type *EltTy = VTy->getElementType();
812    if (SV->getType() != EltTy)
813      SV = Builder.CreateBitCast(SV, EltTy);
814    uint64_t EltSize = TD.getTypeAllocSizeInBits(EltTy);
815    unsigned Elt = Offset/EltSize;
816    return Builder.CreateInsertElement(Old, SV, Builder.getInt32(Elt));
817  }
818
819  // If SV is a first-class aggregate value, insert each value recursively.
820  if (StructType *ST = dyn_cast<StructType>(SV->getType())) {
821    const StructLayout &Layout = *TD.getStructLayout(ST);
822    for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
823      Value *Elt = Builder.CreateExtractValue(SV, i);
824      Old = ConvertScalar_InsertValue(Elt, Old,
825                                      Offset+Layout.getElementOffsetInBits(i),
826                                      Builder);
827    }
828    return Old;
829  }
830
831  if (ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
832    uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
833    for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
834      Value *Elt = Builder.CreateExtractValue(SV, i);
835      Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
836    }
837    return Old;
838  }
839
840  // If SV is a float, convert it to the appropriate integer type.
841  // If it is a pointer, do the same.
842  unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
843  unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
844  unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
845  unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
846  if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
847    SV = Builder.CreateBitCast(SV, IntegerType::get(SV->getContext(),SrcWidth));
848  else if (SV->getType()->isPointerTy())
849    SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()));
850
851  // Zero extend or truncate the value if needed.
852  if (SV->getType() != AllocaType) {
853    if (SV->getType()->getPrimitiveSizeInBits() <
854             AllocaType->getPrimitiveSizeInBits())
855      SV = Builder.CreateZExt(SV, AllocaType);
856    else {
857      // Truncation may be needed if storing more than the alloca can hold
858      // (undefined behavior).
859      SV = Builder.CreateTrunc(SV, AllocaType);
860      SrcWidth = DestWidth;
861      SrcStoreWidth = DestStoreWidth;
862    }
863  }
864
865  // If this is a big-endian system and the store is narrower than the
866  // full alloca type, we need to do a shift to get the right bits.
867  int ShAmt = 0;
868  if (TD.isBigEndian()) {
869    // On big-endian machines, the lowest bit is stored at the bit offset
870    // from the pointer given by getTypeStoreSizeInBits.  This matters for
871    // integers with a bitwidth that is not a multiple of 8.
872    ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
873  } else {
874    ShAmt = Offset;
875  }
876
877  // Note: we support negative bitwidths (with shr) which are not defined.
878  // We do this to support (f.e.) stores off the end of a structure where
879  // only some bits in the structure are set.
880  APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
881  if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
882    SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(), ShAmt));
883    Mask <<= ShAmt;
884  } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
885    SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(), -ShAmt));
886    Mask = Mask.lshr(-ShAmt);
887  }
888
889  // Mask out the bits we are about to insert from the old value, and or
890  // in the new bits.
891  if (SrcWidth != DestWidth) {
892    assert(DestWidth > SrcWidth);
893    Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
894    SV = Builder.CreateOr(Old, SV, "ins");
895  }
896  return SV;
897}
898
899
900//===----------------------------------------------------------------------===//
901// SRoA Driver
902//===----------------------------------------------------------------------===//
903
904
905bool SROA::runOnFunction(Function &F) {
906  TD = getAnalysisIfAvailable<TargetData>();
907
908  bool Changed = performPromotion(F);
909
910  // FIXME: ScalarRepl currently depends on TargetData more than it
911  // theoretically needs to. It should be refactored in order to support
912  // target-independent IR. Until this is done, just skip the actual
913  // scalar-replacement portion of this pass.
914  if (!TD) return Changed;
915
916  while (1) {
917    bool LocalChange = performScalarRepl(F);
918    if (!LocalChange) break;   // No need to repromote if no scalarrepl
919    Changed = true;
920    LocalChange = performPromotion(F);
921    if (!LocalChange) break;   // No need to re-scalarrepl if no promotion
922  }
923
924  return Changed;
925}
926
927namespace {
928class AllocaPromoter : public LoadAndStorePromoter {
929  AllocaInst *AI;
930  DIBuilder *DIB;
931  SmallVector<DbgDeclareInst *, 4> DDIs;
932  SmallVector<DbgValueInst *, 4> DVIs;
933public:
934  AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
935                 DIBuilder *DB)
936    : LoadAndStorePromoter(Insts, S), AI(0), DIB(DB) {}
937
938  void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
939    // Remember which alloca we're promoting (for isInstInList).
940    this->AI = AI;
941    if (MDNode *DebugNode = MDNode::getIfExists(AI->getContext(), AI)) {
942      for (Value::use_iterator UI = DebugNode->use_begin(),
943             E = DebugNode->use_end(); UI != E; ++UI)
944        if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
945          DDIs.push_back(DDI);
946        else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
947          DVIs.push_back(DVI);
948    }
949
950    LoadAndStorePromoter::run(Insts);
951    AI->eraseFromParent();
952    for (SmallVector<DbgDeclareInst *, 4>::iterator I = DDIs.begin(),
953           E = DDIs.end(); I != E; ++I) {
954      DbgDeclareInst *DDI = *I;
955      DDI->eraseFromParent();
956    }
957    for (SmallVector<DbgValueInst *, 4>::iterator I = DVIs.begin(),
958           E = DVIs.end(); I != E; ++I) {
959      DbgValueInst *DVI = *I;
960      DVI->eraseFromParent();
961    }
962  }
963
964  virtual bool isInstInList(Instruction *I,
965                            const SmallVectorImpl<Instruction*> &Insts) const {
966    if (LoadInst *LI = dyn_cast<LoadInst>(I))
967      return LI->getOperand(0) == AI;
968    return cast<StoreInst>(I)->getPointerOperand() == AI;
969  }
970
971  virtual void updateDebugInfo(Instruction *Inst) const {
972    for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(),
973           E = DDIs.end(); I != E; ++I) {
974      DbgDeclareInst *DDI = *I;
975      if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
976        ConvertDebugDeclareToDebugValue(DDI, SI, *DIB);
977      else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
978        ConvertDebugDeclareToDebugValue(DDI, LI, *DIB);
979    }
980    for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
981           E = DVIs.end(); I != E; ++I) {
982      DbgValueInst *DVI = *I;
983      if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
984        Instruction *DbgVal = NULL;
985        // If an argument is zero extended then use argument directly. The ZExt
986        // may be zapped by an optimization pass in future.
987        Argument *ExtendedArg = NULL;
988        if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
989          ExtendedArg = dyn_cast<Argument>(ZExt->getOperand(0));
990        if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
991          ExtendedArg = dyn_cast<Argument>(SExt->getOperand(0));
992        if (ExtendedArg)
993          DbgVal = DIB->insertDbgValueIntrinsic(ExtendedArg, 0,
994                                                DIVariable(DVI->getVariable()),
995                                                SI);
996        else
997          DbgVal = DIB->insertDbgValueIntrinsic(SI->getOperand(0), 0,
998                                                DIVariable(DVI->getVariable()),
999                                                SI);
1000        DbgVal->setDebugLoc(DVI->getDebugLoc());
1001      } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1002        Instruction *DbgVal =
1003          DIB->insertDbgValueIntrinsic(LI->getOperand(0), 0,
1004                                       DIVariable(DVI->getVariable()), LI);
1005        DbgVal->setDebugLoc(DVI->getDebugLoc());
1006      }
1007    }
1008  }
1009};
1010} // end anon namespace
1011
1012/// isSafeSelectToSpeculate - Select instructions that use an alloca and are
1013/// subsequently loaded can be rewritten to load both input pointers and then
1014/// select between the result, allowing the load of the alloca to be promoted.
1015/// From this:
1016///   %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1017///   %V = load i32* %P2
1018/// to:
1019///   %V1 = load i32* %Alloca      -> will be mem2reg'd
1020///   %V2 = load i32* %Other
1021///   %V = select i1 %cond, i32 %V1, i32 %V2
1022///
1023/// We can do this to a select if its only uses are loads and if the operand to
1024/// the select can be loaded unconditionally.
1025static bool isSafeSelectToSpeculate(SelectInst *SI, const TargetData *TD) {
1026  bool TDerefable = SI->getTrueValue()->isDereferenceablePointer();
1027  bool FDerefable = SI->getFalseValue()->isDereferenceablePointer();
1028
1029  for (Value::use_iterator UI = SI->use_begin(), UE = SI->use_end();
1030       UI != UE; ++UI) {
1031    LoadInst *LI = dyn_cast<LoadInst>(*UI);
1032    if (LI == 0 || !LI->isSimple()) return false;
1033
1034    // Both operands to the select need to be dereferencable, either absolutely
1035    // (e.g. allocas) or at this point because we can see other accesses to it.
1036    if (!TDerefable && !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
1037                                                    LI->getAlignment(), TD))
1038      return false;
1039    if (!FDerefable && !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
1040                                                    LI->getAlignment(), TD))
1041      return false;
1042  }
1043
1044  return true;
1045}
1046
1047/// isSafePHIToSpeculate - PHI instructions that use an alloca and are
1048/// subsequently loaded can be rewritten to load both input pointers in the pred
1049/// blocks and then PHI the results, allowing the load of the alloca to be
1050/// promoted.
1051/// From this:
1052///   %P2 = phi [i32* %Alloca, i32* %Other]
1053///   %V = load i32* %P2
1054/// to:
1055///   %V1 = load i32* %Alloca      -> will be mem2reg'd
1056///   ...
1057///   %V2 = load i32* %Other
1058///   ...
1059///   %V = phi [i32 %V1, i32 %V2]
1060///
1061/// We can do this to a select if its only uses are loads and if the operand to
1062/// the select can be loaded unconditionally.
1063static bool isSafePHIToSpeculate(PHINode *PN, const TargetData *TD) {
1064  // For now, we can only do this promotion if the load is in the same block as
1065  // the PHI, and if there are no stores between the phi and load.
1066  // TODO: Allow recursive phi users.
1067  // TODO: Allow stores.
1068  BasicBlock *BB = PN->getParent();
1069  unsigned MaxAlign = 0;
1070  for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
1071       UI != UE; ++UI) {
1072    LoadInst *LI = dyn_cast<LoadInst>(*UI);
1073    if (LI == 0 || !LI->isSimple()) return false;
1074
1075    // For now we only allow loads in the same block as the PHI.  This is a
1076    // common case that happens when instcombine merges two loads through a PHI.
1077    if (LI->getParent() != BB) return false;
1078
1079    // Ensure that there are no instructions between the PHI and the load that
1080    // could store.
1081    for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
1082      if (BBI->mayWriteToMemory())
1083        return false;
1084
1085    MaxAlign = std::max(MaxAlign, LI->getAlignment());
1086  }
1087
1088  // Okay, we know that we have one or more loads in the same block as the PHI.
1089  // We can transform this if it is safe to push the loads into the predecessor
1090  // blocks.  The only thing to watch out for is that we can't put a possibly
1091  // trapping load in the predecessor if it is a critical edge.
1092  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1093    BasicBlock *Pred = PN->getIncomingBlock(i);
1094    Value *InVal = PN->getIncomingValue(i);
1095
1096    // If the terminator of the predecessor has side-effects (an invoke),
1097    // there is no safe place to put a load in the predecessor.
1098    if (Pred->getTerminator()->mayHaveSideEffects())
1099      return false;
1100
1101    // If the value is produced by the terminator of the predecessor
1102    // (an invoke), there is no valid place to put a load in the predecessor.
1103    if (Pred->getTerminator() == InVal)
1104      return false;
1105
1106    // If the predecessor has a single successor, then the edge isn't critical.
1107    if (Pred->getTerminator()->getNumSuccessors() == 1)
1108      continue;
1109
1110    // If this pointer is always safe to load, or if we can prove that there is
1111    // already a load in the block, then we can move the load to the pred block.
1112    if (InVal->isDereferenceablePointer() ||
1113        isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign, TD))
1114      continue;
1115
1116    return false;
1117  }
1118
1119  return true;
1120}
1121
1122
1123/// tryToMakeAllocaBePromotable - This returns true if the alloca only has
1124/// direct (non-volatile) loads and stores to it.  If the alloca is close but
1125/// not quite there, this will transform the code to allow promotion.  As such,
1126/// it is a non-pure predicate.
1127static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const TargetData *TD) {
1128  SetVector<Instruction*, SmallVector<Instruction*, 4>,
1129            SmallPtrSet<Instruction*, 4> > InstsToRewrite;
1130
1131  for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
1132       UI != UE; ++UI) {
1133    User *U = *UI;
1134    if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1135      if (!LI->isSimple())
1136        return false;
1137      continue;
1138    }
1139
1140    if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1141      if (SI->getOperand(0) == AI || !SI->isSimple())
1142        return false;   // Don't allow a store OF the AI, only INTO the AI.
1143      continue;
1144    }
1145
1146    if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
1147      // If the condition being selected on is a constant, fold the select, yes
1148      // this does (rarely) happen early on.
1149      if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
1150        Value *Result = SI->getOperand(1+CI->isZero());
1151        SI->replaceAllUsesWith(Result);
1152        SI->eraseFromParent();
1153
1154        // This is very rare and we just scrambled the use list of AI, start
1155        // over completely.
1156        return tryToMakeAllocaBePromotable(AI, TD);
1157      }
1158
1159      // If it is safe to turn "load (select c, AI, ptr)" into a select of two
1160      // loads, then we can transform this by rewriting the select.
1161      if (!isSafeSelectToSpeculate(SI, TD))
1162        return false;
1163
1164      InstsToRewrite.insert(SI);
1165      continue;
1166    }
1167
1168    if (PHINode *PN = dyn_cast<PHINode>(U)) {
1169      if (PN->use_empty()) {  // Dead PHIs can be stripped.
1170        InstsToRewrite.insert(PN);
1171        continue;
1172      }
1173
1174      // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
1175      // in the pred blocks, then we can transform this by rewriting the PHI.
1176      if (!isSafePHIToSpeculate(PN, TD))
1177        return false;
1178
1179      InstsToRewrite.insert(PN);
1180      continue;
1181    }
1182
1183    if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
1184      if (onlyUsedByLifetimeMarkers(BCI)) {
1185        InstsToRewrite.insert(BCI);
1186        continue;
1187      }
1188    }
1189
1190    return false;
1191  }
1192
1193  // If there are no instructions to rewrite, then all uses are load/stores and
1194  // we're done!
1195  if (InstsToRewrite.empty())
1196    return true;
1197
1198  // If we have instructions that need to be rewritten for this to be promotable
1199  // take care of it now.
1200  for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
1201    if (BitCastInst *BCI = dyn_cast<BitCastInst>(InstsToRewrite[i])) {
1202      // This could only be a bitcast used by nothing but lifetime intrinsics.
1203      for (BitCastInst::use_iterator I = BCI->use_begin(), E = BCI->use_end();
1204           I != E;) {
1205        Use &U = I.getUse();
1206        ++I;
1207        cast<Instruction>(U.getUser())->eraseFromParent();
1208      }
1209      BCI->eraseFromParent();
1210      continue;
1211    }
1212
1213    if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
1214      // Selects in InstsToRewrite only have load uses.  Rewrite each as two
1215      // loads with a new select.
1216      while (!SI->use_empty()) {
1217        LoadInst *LI = cast<LoadInst>(SI->use_back());
1218
1219        IRBuilder<> Builder(LI);
1220        LoadInst *TrueLoad =
1221          Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t");
1222        LoadInst *FalseLoad =
1223          Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".f");
1224
1225        // Transfer alignment and TBAA info if present.
1226        TrueLoad->setAlignment(LI->getAlignment());
1227        FalseLoad->setAlignment(LI->getAlignment());
1228        if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1229          TrueLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1230          FalseLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1231        }
1232
1233        Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
1234        V->takeName(LI);
1235        LI->replaceAllUsesWith(V);
1236        LI->eraseFromParent();
1237      }
1238
1239      // Now that all the loads are gone, the select is gone too.
1240      SI->eraseFromParent();
1241      continue;
1242    }
1243
1244    // Otherwise, we have a PHI node which allows us to push the loads into the
1245    // predecessors.
1246    PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
1247    if (PN->use_empty()) {
1248      PN->eraseFromParent();
1249      continue;
1250    }
1251
1252    Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
1253    PHINode *NewPN = PHINode::Create(LoadTy, PN->getNumIncomingValues(),
1254                                     PN->getName()+".ld", PN);
1255
1256    // Get the TBAA tag and alignment to use from one of the loads.  It doesn't
1257    // matter which one we get and if any differ, it doesn't matter.
1258    LoadInst *SomeLoad = cast<LoadInst>(PN->use_back());
1259    MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1260    unsigned Align = SomeLoad->getAlignment();
1261
1262    // Rewrite all loads of the PN to use the new PHI.
1263    while (!PN->use_empty()) {
1264      LoadInst *LI = cast<LoadInst>(PN->use_back());
1265      LI->replaceAllUsesWith(NewPN);
1266      LI->eraseFromParent();
1267    }
1268
1269    // Inject loads into all of the pred blocks.  Keep track of which blocks we
1270    // insert them into in case we have multiple edges from the same block.
1271    DenseMap<BasicBlock*, LoadInst*> InsertedLoads;
1272
1273    for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1274      BasicBlock *Pred = PN->getIncomingBlock(i);
1275      LoadInst *&Load = InsertedLoads[Pred];
1276      if (Load == 0) {
1277        Load = new LoadInst(PN->getIncomingValue(i),
1278                            PN->getName() + "." + Pred->getName(),
1279                            Pred->getTerminator());
1280        Load->setAlignment(Align);
1281        if (TBAATag) Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1282      }
1283
1284      NewPN->addIncoming(Load, Pred);
1285    }
1286
1287    PN->eraseFromParent();
1288  }
1289
1290  ++NumAdjusted;
1291  return true;
1292}
1293
1294bool SROA::performPromotion(Function &F) {
1295  std::vector<AllocaInst*> Allocas;
1296  DominatorTree *DT = 0;
1297  if (HasDomTree)
1298    DT = &getAnalysis<DominatorTree>();
1299
1300  BasicBlock &BB = F.getEntryBlock();  // Get the entry node for the function
1301  DIBuilder DIB(*F.getParent());
1302  bool Changed = false;
1303  SmallVector<Instruction*, 64> Insts;
1304  while (1) {
1305    Allocas.clear();
1306
1307    // Find allocas that are safe to promote, by looking at all instructions in
1308    // the entry node
1309    for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
1310      if (AllocaInst *AI = dyn_cast<AllocaInst>(I))       // Is it an alloca?
1311        if (tryToMakeAllocaBePromotable(AI, TD))
1312          Allocas.push_back(AI);
1313
1314    if (Allocas.empty()) break;
1315
1316    if (HasDomTree)
1317      PromoteMemToReg(Allocas, *DT);
1318    else {
1319      SSAUpdater SSA;
1320      for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
1321        AllocaInst *AI = Allocas[i];
1322
1323        // Build list of instructions to promote.
1324        for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1325             UI != E; ++UI)
1326          Insts.push_back(cast<Instruction>(*UI));
1327        AllocaPromoter(Insts, SSA, &DIB).run(AI, Insts);
1328        Insts.clear();
1329      }
1330    }
1331    NumPromoted += Allocas.size();
1332    Changed = true;
1333  }
1334
1335  return Changed;
1336}
1337
1338
1339/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
1340/// SROA.  It must be a struct or array type with a small number of elements.
1341static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
1342  Type *T = AI->getAllocatedType();
1343  // Do not promote any struct into more than 32 separate vars.
1344  if (StructType *ST = dyn_cast<StructType>(T))
1345    return ST->getNumElements() <= 32;
1346  // Arrays are much less likely to be safe for SROA; only consider
1347  // them if they are very small.
1348  if (ArrayType *AT = dyn_cast<ArrayType>(T))
1349    return AT->getNumElements() <= 8;
1350  return false;
1351}
1352
1353
1354// performScalarRepl - This algorithm is a simple worklist driven algorithm,
1355// which runs on all of the alloca instructions in the function, removing them
1356// if they are only used by getelementptr instructions.
1357//
1358bool SROA::performScalarRepl(Function &F) {
1359  std::vector<AllocaInst*> WorkList;
1360
1361  // Scan the entry basic block, adding allocas to the worklist.
1362  BasicBlock &BB = F.getEntryBlock();
1363  for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
1364    if (AllocaInst *A = dyn_cast<AllocaInst>(I))
1365      WorkList.push_back(A);
1366
1367  // Process the worklist
1368  bool Changed = false;
1369  while (!WorkList.empty()) {
1370    AllocaInst *AI = WorkList.back();
1371    WorkList.pop_back();
1372
1373    // Handle dead allocas trivially.  These can be formed by SROA'ing arrays
1374    // with unused elements.
1375    if (AI->use_empty()) {
1376      AI->eraseFromParent();
1377      Changed = true;
1378      continue;
1379    }
1380
1381    // If this alloca is impossible for us to promote, reject it early.
1382    if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
1383      continue;
1384
1385    // Check to see if this allocation is only modified by a memcpy/memmove from
1386    // a constant global.  If this is the case, we can change all users to use
1387    // the constant global instead.  This is commonly produced by the CFE by
1388    // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
1389    // is only subsequently read.
1390    SmallVector<Instruction *, 4> ToDelete;
1391    if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(AI, ToDelete)) {
1392      DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
1393      DEBUG(dbgs() << "  memcpy = " << *Copy << '\n');
1394      for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
1395        ToDelete[i]->eraseFromParent();
1396      Constant *TheSrc = cast<Constant>(Copy->getSource());
1397      AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
1398      Copy->eraseFromParent();  // Don't mutate the global.
1399      AI->eraseFromParent();
1400      ++NumGlobals;
1401      Changed = true;
1402      continue;
1403    }
1404
1405    // Check to see if we can perform the core SROA transformation.  We cannot
1406    // transform the allocation instruction if it is an array allocation
1407    // (allocations OF arrays are ok though), and an allocation of a scalar
1408    // value cannot be decomposed at all.
1409    uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
1410
1411    // Do not promote [0 x %struct].
1412    if (AllocaSize == 0) continue;
1413
1414    // Do not promote any struct whose size is too big.
1415    if (AllocaSize > SRThreshold) continue;
1416
1417    // If the alloca looks like a good candidate for scalar replacement, and if
1418    // all its users can be transformed, then split up the aggregate into its
1419    // separate elements.
1420    if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
1421      DoScalarReplacement(AI, WorkList);
1422      Changed = true;
1423      continue;
1424    }
1425
1426    // If we can turn this aggregate value (potentially with casts) into a
1427    // simple scalar value that can be mem2reg'd into a register value.
1428    // IsNotTrivial tracks whether this is something that mem2reg could have
1429    // promoted itself.  If so, we don't want to transform it needlessly.  Note
1430    // that we can't just check based on the type: the alloca may be of an i32
1431    // but that has pointer arithmetic to set byte 3 of it or something.
1432    if (AllocaInst *NewAI =
1433          ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
1434      NewAI->takeName(AI);
1435      AI->eraseFromParent();
1436      ++NumConverted;
1437      Changed = true;
1438      continue;
1439    }
1440
1441    // Otherwise, couldn't process this alloca.
1442  }
1443
1444  return Changed;
1445}
1446
1447/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1448/// predicate, do SROA now.
1449void SROA::DoScalarReplacement(AllocaInst *AI,
1450                               std::vector<AllocaInst*> &WorkList) {
1451  DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
1452  SmallVector<AllocaInst*, 32> ElementAllocas;
1453  if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1454    ElementAllocas.reserve(ST->getNumContainedTypes());
1455    for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
1456      AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
1457                                      AI->getAlignment(),
1458                                      AI->getName() + "." + Twine(i), AI);
1459      ElementAllocas.push_back(NA);
1460      WorkList.push_back(NA);  // Add to worklist for recursive processing
1461    }
1462  } else {
1463    ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
1464    ElementAllocas.reserve(AT->getNumElements());
1465    Type *ElTy = AT->getElementType();
1466    for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1467      AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
1468                                      AI->getName() + "." + Twine(i), AI);
1469      ElementAllocas.push_back(NA);
1470      WorkList.push_back(NA);  // Add to worklist for recursive processing
1471    }
1472  }
1473
1474  // Now that we have created the new alloca instructions, rewrite all the
1475  // uses of the old alloca.
1476  RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
1477
1478  // Now erase any instructions that were made dead while rewriting the alloca.
1479  DeleteDeadInstructions();
1480  AI->eraseFromParent();
1481
1482  ++NumReplaced;
1483}
1484
1485/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1486/// recursively including all their operands that become trivially dead.
1487void SROA::DeleteDeadInstructions() {
1488  while (!DeadInsts.empty()) {
1489    Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
1490
1491    for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1492      if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1493        // Zero out the operand and see if it becomes trivially dead.
1494        // (But, don't add allocas to the dead instruction list -- they are
1495        // already on the worklist and will be deleted separately.)
1496        *OI = 0;
1497        if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1498          DeadInsts.push_back(U);
1499      }
1500
1501    I->eraseFromParent();
1502  }
1503}
1504
1505/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1506/// performing scalar replacement of alloca AI.  The results are flagged in
1507/// the Info parameter.  Offset indicates the position within AI that is
1508/// referenced by this instruction.
1509void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
1510                               AllocaInfo &Info) {
1511  for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1512    Instruction *User = cast<Instruction>(*UI);
1513
1514    if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1515      isSafeForScalarRepl(BC, Offset, Info);
1516    } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1517      uint64_t GEPOffset = Offset;
1518      isSafeGEP(GEPI, GEPOffset, Info);
1519      if (!Info.isUnsafe)
1520        isSafeForScalarRepl(GEPI, GEPOffset, Info);
1521    } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1522      ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1523      if (Length == 0)
1524        return MarkUnsafe(Info, User);
1525      isSafeMemAccess(Offset, Length->getZExtValue(), 0,
1526                      UI.getOperandNo() == 0, Info, MI,
1527                      true /*AllowWholeAccess*/);
1528    } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1529      if (!LI->isSimple())
1530        return MarkUnsafe(Info, User);
1531      Type *LIType = LI->getType();
1532      isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
1533                      LIType, false, Info, LI, true /*AllowWholeAccess*/);
1534      Info.hasALoadOrStore = true;
1535
1536    } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1537      // Store is ok if storing INTO the pointer, not storing the pointer
1538      if (!SI->isSimple() || SI->getOperand(0) == I)
1539        return MarkUnsafe(Info, User);
1540
1541      Type *SIType = SI->getOperand(0)->getType();
1542      isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
1543                      SIType, true, Info, SI, true /*AllowWholeAccess*/);
1544      Info.hasALoadOrStore = true;
1545    } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
1546      if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1547          II->getIntrinsicID() != Intrinsic::lifetime_end)
1548        return MarkUnsafe(Info, User);
1549    } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1550      isSafePHISelectUseForScalarRepl(User, Offset, Info);
1551    } else {
1552      return MarkUnsafe(Info, User);
1553    }
1554    if (Info.isUnsafe) return;
1555  }
1556}
1557
1558
1559/// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
1560/// derived from the alloca, we can often still split the alloca into elements.
1561/// This is useful if we have a large alloca where one element is phi'd
1562/// together somewhere: we can SRoA and promote all the other elements even if
1563/// we end up not being able to promote this one.
1564///
1565/// All we require is that the uses of the PHI do not index into other parts of
1566/// the alloca.  The most important use case for this is single load and stores
1567/// that are PHI'd together, which can happen due to code sinking.
1568void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
1569                                           AllocaInfo &Info) {
1570  // If we've already checked this PHI, don't do it again.
1571  if (PHINode *PN = dyn_cast<PHINode>(I))
1572    if (!Info.CheckedPHIs.insert(PN))
1573      return;
1574
1575  for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1576    Instruction *User = cast<Instruction>(*UI);
1577
1578    if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1579      isSafePHISelectUseForScalarRepl(BC, Offset, Info);
1580    } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1581      // Only allow "bitcast" GEPs for simplicity.  We could generalize this,
1582      // but would have to prove that we're staying inside of an element being
1583      // promoted.
1584      if (!GEPI->hasAllZeroIndices())
1585        return MarkUnsafe(Info, User);
1586      isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
1587    } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1588      if (!LI->isSimple())
1589        return MarkUnsafe(Info, User);
1590      Type *LIType = LI->getType();
1591      isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
1592                      LIType, false, Info, LI, false /*AllowWholeAccess*/);
1593      Info.hasALoadOrStore = true;
1594
1595    } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1596      // Store is ok if storing INTO the pointer, not storing the pointer
1597      if (!SI->isSimple() || SI->getOperand(0) == I)
1598        return MarkUnsafe(Info, User);
1599
1600      Type *SIType = SI->getOperand(0)->getType();
1601      isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
1602                      SIType, true, Info, SI, false /*AllowWholeAccess*/);
1603      Info.hasALoadOrStore = true;
1604    } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1605      isSafePHISelectUseForScalarRepl(User, Offset, Info);
1606    } else {
1607      return MarkUnsafe(Info, User);
1608    }
1609    if (Info.isUnsafe) return;
1610  }
1611}
1612
1613/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1614/// replacement.  It is safe when all the indices are constant, in-bounds
1615/// references, and when the resulting offset corresponds to an element within
1616/// the alloca type.  The results are flagged in the Info parameter.  Upon
1617/// return, Offset is adjusted as specified by the GEP indices.
1618void SROA::isSafeGEP(GetElementPtrInst *GEPI,
1619                     uint64_t &Offset, AllocaInfo &Info) {
1620  gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1621  if (GEPIt == E)
1622    return;
1623
1624  // Walk through the GEP type indices, checking the types that this indexes
1625  // into.
1626  for (; GEPIt != E; ++GEPIt) {
1627    // Ignore struct elements, no extra checking needed for these.
1628    if ((*GEPIt)->isStructTy())
1629      continue;
1630
1631    ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1632    if (!IdxVal)
1633      return MarkUnsafe(Info, GEPI);
1634  }
1635
1636  // Compute the offset due to this GEP and check if the alloca has a
1637  // component element at that offset.
1638  SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1639  Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
1640  if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset, 0))
1641    MarkUnsafe(Info, GEPI);
1642}
1643
1644/// isHomogeneousAggregate - Check if type T is a struct or array containing
1645/// elements of the same type (which is always true for arrays).  If so,
1646/// return true with NumElts and EltTy set to the number of elements and the
1647/// element type, respectively.
1648static bool isHomogeneousAggregate(Type *T, unsigned &NumElts,
1649                                   Type *&EltTy) {
1650  if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
1651    NumElts = AT->getNumElements();
1652    EltTy = (NumElts == 0 ? 0 : AT->getElementType());
1653    return true;
1654  }
1655  if (StructType *ST = dyn_cast<StructType>(T)) {
1656    NumElts = ST->getNumContainedTypes();
1657    EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
1658    for (unsigned n = 1; n < NumElts; ++n) {
1659      if (ST->getContainedType(n) != EltTy)
1660        return false;
1661    }
1662    return true;
1663  }
1664  return false;
1665}
1666
1667/// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1668/// "homogeneous" aggregates with the same element type and number of elements.
1669static bool isCompatibleAggregate(Type *T1, Type *T2) {
1670  if (T1 == T2)
1671    return true;
1672
1673  unsigned NumElts1, NumElts2;
1674  Type *EltTy1, *EltTy2;
1675  if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1676      isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1677      NumElts1 == NumElts2 &&
1678      EltTy1 == EltTy2)
1679    return true;
1680
1681  return false;
1682}
1683
1684/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1685/// alloca or has an offset and size that corresponds to a component element
1686/// within it.  The offset checked here may have been formed from a GEP with a
1687/// pointer bitcasted to a different type.
1688///
1689/// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
1690/// unit.  If false, it only allows accesses known to be in a single element.
1691void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
1692                           Type *MemOpType, bool isStore,
1693                           AllocaInfo &Info, Instruction *TheAccess,
1694                           bool AllowWholeAccess) {
1695  // Check if this is a load/store of the entire alloca.
1696  if (Offset == 0 && AllowWholeAccess &&
1697      MemSize == TD->getTypeAllocSize(Info.AI->getAllocatedType())) {
1698    // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1699    // loads/stores (which are essentially the same as the MemIntrinsics with
1700    // regard to copying padding between elements).  But, if an alloca is
1701    // flagged as both a source and destination of such operations, we'll need
1702    // to check later for padding between elements.
1703    if (!MemOpType || MemOpType->isIntegerTy()) {
1704      if (isStore)
1705        Info.isMemCpyDst = true;
1706      else
1707        Info.isMemCpySrc = true;
1708      return;
1709    }
1710    // This is also safe for references using a type that is compatible with
1711    // the type of the alloca, so that loads/stores can be rewritten using
1712    // insertvalue/extractvalue.
1713    if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
1714      Info.hasSubelementAccess = true;
1715      return;
1716    }
1717  }
1718  // Check if the offset/size correspond to a component within the alloca type.
1719  Type *T = Info.AI->getAllocatedType();
1720  if (TypeHasComponent(T, Offset, MemSize)) {
1721    Info.hasSubelementAccess = true;
1722    return;
1723  }
1724
1725  return MarkUnsafe(Info, TheAccess);
1726}
1727
1728/// TypeHasComponent - Return true if T has a component type with the
1729/// specified offset and size.  If Size is zero, do not check the size.
1730bool SROA::TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size) {
1731  Type *EltTy;
1732  uint64_t EltSize;
1733  if (StructType *ST = dyn_cast<StructType>(T)) {
1734    const StructLayout *Layout = TD->getStructLayout(ST);
1735    unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1736    EltTy = ST->getContainedType(EltIdx);
1737    EltSize = TD->getTypeAllocSize(EltTy);
1738    Offset -= Layout->getElementOffset(EltIdx);
1739  } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
1740    EltTy = AT->getElementType();
1741    EltSize = TD->getTypeAllocSize(EltTy);
1742    if (Offset >= AT->getNumElements() * EltSize)
1743      return false;
1744    Offset %= EltSize;
1745  } else {
1746    return false;
1747  }
1748  if (Offset == 0 && (Size == 0 || EltSize == Size))
1749    return true;
1750  // Check if the component spans multiple elements.
1751  if (Offset + Size > EltSize)
1752    return false;
1753  return TypeHasComponent(EltTy, Offset, Size);
1754}
1755
1756/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1757/// the instruction I, which references it, to use the separate elements.
1758/// Offset indicates the position within AI that is referenced by this
1759/// instruction.
1760void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1761                                SmallVector<AllocaInst*, 32> &NewElts) {
1762  for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
1763    Use &TheUse = UI.getUse();
1764    Instruction *User = cast<Instruction>(*UI++);
1765
1766    if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1767      RewriteBitCast(BC, AI, Offset, NewElts);
1768      continue;
1769    }
1770
1771    if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1772      RewriteGEP(GEPI, AI, Offset, NewElts);
1773      continue;
1774    }
1775
1776    if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1777      ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1778      uint64_t MemSize = Length->getZExtValue();
1779      if (Offset == 0 &&
1780          MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1781        RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
1782      // Otherwise the intrinsic can only touch a single element and the
1783      // address operand will be updated, so nothing else needs to be done.
1784      continue;
1785    }
1786
1787    if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
1788      if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
1789          II->getIntrinsicID() == Intrinsic::lifetime_end) {
1790        RewriteLifetimeIntrinsic(II, AI, Offset, NewElts);
1791      }
1792      continue;
1793    }
1794
1795    if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1796      Type *LIType = LI->getType();
1797
1798      if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
1799        // Replace:
1800        //   %res = load { i32, i32 }* %alloc
1801        // with:
1802        //   %load.0 = load i32* %alloc.0
1803        //   %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1804        //   %load.1 = load i32* %alloc.1
1805        //   %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1806        // (Also works for arrays instead of structs)
1807        Value *Insert = UndefValue::get(LIType);
1808        IRBuilder<> Builder(LI);
1809        for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1810          Value *Load = Builder.CreateLoad(NewElts[i], "load");
1811          Insert = Builder.CreateInsertValue(Insert, Load, i, "insert");
1812        }
1813        LI->replaceAllUsesWith(Insert);
1814        DeadInsts.push_back(LI);
1815      } else if (LIType->isIntegerTy() &&
1816                 TD->getTypeAllocSize(LIType) ==
1817                 TD->getTypeAllocSize(AI->getAllocatedType())) {
1818        // If this is a load of the entire alloca to an integer, rewrite it.
1819        RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1820      }
1821      continue;
1822    }
1823
1824    if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1825      Value *Val = SI->getOperand(0);
1826      Type *SIType = Val->getType();
1827      if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
1828        // Replace:
1829        //   store { i32, i32 } %val, { i32, i32 }* %alloc
1830        // with:
1831        //   %val.0 = extractvalue { i32, i32 } %val, 0
1832        //   store i32 %val.0, i32* %alloc.0
1833        //   %val.1 = extractvalue { i32, i32 } %val, 1
1834        //   store i32 %val.1, i32* %alloc.1
1835        // (Also works for arrays instead of structs)
1836        IRBuilder<> Builder(SI);
1837        for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1838          Value *Extract = Builder.CreateExtractValue(Val, i, Val->getName());
1839          Builder.CreateStore(Extract, NewElts[i]);
1840        }
1841        DeadInsts.push_back(SI);
1842      } else if (SIType->isIntegerTy() &&
1843                 TD->getTypeAllocSize(SIType) ==
1844                 TD->getTypeAllocSize(AI->getAllocatedType())) {
1845        // If this is a store of the entire alloca from an integer, rewrite it.
1846        RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1847      }
1848      continue;
1849    }
1850
1851    if (isa<SelectInst>(User) || isa<PHINode>(User)) {
1852      // If we have a PHI user of the alloca itself (as opposed to a GEP or
1853      // bitcast) we have to rewrite it.  GEP and bitcast uses will be RAUW'd to
1854      // the new pointer.
1855      if (!isa<AllocaInst>(I)) continue;
1856
1857      assert(Offset == 0 && NewElts[0] &&
1858             "Direct alloca use should have a zero offset");
1859
1860      // If we have a use of the alloca, we know the derived uses will be
1861      // utilizing just the first element of the scalarized result.  Insert a
1862      // bitcast of the first alloca before the user as required.
1863      AllocaInst *NewAI = NewElts[0];
1864      BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
1865      NewAI->moveBefore(BCI);
1866      TheUse = BCI;
1867      continue;
1868    }
1869  }
1870}
1871
1872/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1873/// and recursively continue updating all of its uses.
1874void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1875                          SmallVector<AllocaInst*, 32> &NewElts) {
1876  RewriteForScalarRepl(BC, AI, Offset, NewElts);
1877  if (BC->getOperand(0) != AI)
1878    return;
1879
1880  // The bitcast references the original alloca.  Replace its uses with
1881  // references to the alloca containing offset zero (which is normally at
1882  // index zero, but might not be in cases involving structs with elements
1883  // of size zero).
1884  Type *T = AI->getAllocatedType();
1885  uint64_t EltOffset = 0;
1886  Type *IdxTy;
1887  uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
1888  Instruction *Val = NewElts[Idx];
1889  if (Val->getType() != BC->getDestTy()) {
1890    Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1891    Val->takeName(BC);
1892  }
1893  BC->replaceAllUsesWith(Val);
1894  DeadInsts.push_back(BC);
1895}
1896
1897/// FindElementAndOffset - Return the index of the element containing Offset
1898/// within the specified type, which must be either a struct or an array.
1899/// Sets T to the type of the element and Offset to the offset within that
1900/// element.  IdxTy is set to the type of the index result to be used in a
1901/// GEP instruction.
1902uint64_t SROA::FindElementAndOffset(Type *&T, uint64_t &Offset,
1903                                    Type *&IdxTy) {
1904  uint64_t Idx = 0;
1905  if (StructType *ST = dyn_cast<StructType>(T)) {
1906    const StructLayout *Layout = TD->getStructLayout(ST);
1907    Idx = Layout->getElementContainingOffset(Offset);
1908    T = ST->getContainedType(Idx);
1909    Offset -= Layout->getElementOffset(Idx);
1910    IdxTy = Type::getInt32Ty(T->getContext());
1911    return Idx;
1912  }
1913  ArrayType *AT = cast<ArrayType>(T);
1914  T = AT->getElementType();
1915  uint64_t EltSize = TD->getTypeAllocSize(T);
1916  Idx = Offset / EltSize;
1917  Offset -= Idx * EltSize;
1918  IdxTy = Type::getInt64Ty(T->getContext());
1919  return Idx;
1920}
1921
1922/// RewriteGEP - Check if this GEP instruction moves the pointer across
1923/// elements of the alloca that are being split apart, and if so, rewrite
1924/// the GEP to be relative to the new element.
1925void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1926                      SmallVector<AllocaInst*, 32> &NewElts) {
1927  uint64_t OldOffset = Offset;
1928  SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1929  Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
1930
1931  RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1932
1933  Type *T = AI->getAllocatedType();
1934  Type *IdxTy;
1935  uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
1936  if (GEPI->getOperand(0) == AI)
1937    OldIdx = ~0ULL; // Force the GEP to be rewritten.
1938
1939  T = AI->getAllocatedType();
1940  uint64_t EltOffset = Offset;
1941  uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
1942
1943  // If this GEP does not move the pointer across elements of the alloca
1944  // being split, then it does not needs to be rewritten.
1945  if (Idx == OldIdx)
1946    return;
1947
1948  Type *i32Ty = Type::getInt32Ty(AI->getContext());
1949  SmallVector<Value*, 8> NewArgs;
1950  NewArgs.push_back(Constant::getNullValue(i32Ty));
1951  while (EltOffset != 0) {
1952    uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
1953    NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
1954  }
1955  Instruction *Val = NewElts[Idx];
1956  if (NewArgs.size() > 1) {
1957    Val = GetElementPtrInst::CreateInBounds(Val, NewArgs, "", GEPI);
1958    Val->takeName(GEPI);
1959  }
1960  if (Val->getType() != GEPI->getType())
1961    Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
1962  GEPI->replaceAllUsesWith(Val);
1963  DeadInsts.push_back(GEPI);
1964}
1965
1966/// RewriteLifetimeIntrinsic - II is a lifetime.start/lifetime.end. Rewrite it
1967/// to mark the lifetime of the scalarized memory.
1968void SROA::RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
1969                                    uint64_t Offset,
1970                                    SmallVector<AllocaInst*, 32> &NewElts) {
1971  ConstantInt *OldSize = cast<ConstantInt>(II->getArgOperand(0));
1972  // Put matching lifetime markers on everything from Offset up to
1973  // Offset+OldSize.
1974  Type *AIType = AI->getAllocatedType();
1975  uint64_t NewOffset = Offset;
1976  Type *IdxTy;
1977  uint64_t Idx = FindElementAndOffset(AIType, NewOffset, IdxTy);
1978
1979  IRBuilder<> Builder(II);
1980  uint64_t Size = OldSize->getLimitedValue();
1981
1982  if (NewOffset) {
1983    // Splice the first element and index 'NewOffset' bytes in.  SROA will
1984    // split the alloca again later.
1985    Value *V = Builder.CreateBitCast(NewElts[Idx], Builder.getInt8PtrTy());
1986    V = Builder.CreateGEP(V, Builder.getInt64(NewOffset));
1987
1988    IdxTy = NewElts[Idx]->getAllocatedType();
1989    uint64_t EltSize = TD->getTypeAllocSize(IdxTy) - NewOffset;
1990    if (EltSize > Size) {
1991      EltSize = Size;
1992      Size = 0;
1993    } else {
1994      Size -= EltSize;
1995    }
1996    if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1997      Builder.CreateLifetimeStart(V, Builder.getInt64(EltSize));
1998    else
1999      Builder.CreateLifetimeEnd(V, Builder.getInt64(EltSize));
2000    ++Idx;
2001  }
2002
2003  for (; Idx != NewElts.size() && Size; ++Idx) {
2004    IdxTy = NewElts[Idx]->getAllocatedType();
2005    uint64_t EltSize = TD->getTypeAllocSize(IdxTy);
2006    if (EltSize > Size) {
2007      EltSize = Size;
2008      Size = 0;
2009    } else {
2010      Size -= EltSize;
2011    }
2012    if (II->getIntrinsicID() == Intrinsic::lifetime_start)
2013      Builder.CreateLifetimeStart(NewElts[Idx],
2014                                  Builder.getInt64(EltSize));
2015    else
2016      Builder.CreateLifetimeEnd(NewElts[Idx],
2017                                Builder.getInt64(EltSize));
2018  }
2019  DeadInsts.push_back(II);
2020}
2021
2022/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
2023/// Rewrite it to copy or set the elements of the scalarized memory.
2024void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
2025                                        AllocaInst *AI,
2026                                        SmallVector<AllocaInst*, 32> &NewElts) {
2027  // If this is a memcpy/memmove, construct the other pointer as the
2028  // appropriate type.  The "Other" pointer is the pointer that goes to memory
2029  // that doesn't have anything to do with the alloca that we are promoting. For
2030  // memset, this Value* stays null.
2031  Value *OtherPtr = 0;
2032  unsigned MemAlignment = MI->getAlignment();
2033  if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
2034    if (Inst == MTI->getRawDest())
2035      OtherPtr = MTI->getRawSource();
2036    else {
2037      assert(Inst == MTI->getRawSource());
2038      OtherPtr = MTI->getRawDest();
2039    }
2040  }
2041
2042  // If there is an other pointer, we want to convert it to the same pointer
2043  // type as AI has, so we can GEP through it safely.
2044  if (OtherPtr) {
2045    unsigned AddrSpace =
2046      cast<PointerType>(OtherPtr->getType())->getAddressSpace();
2047
2048    // Remove bitcasts and all-zero GEPs from OtherPtr.  This is an
2049    // optimization, but it's also required to detect the corner case where
2050    // both pointer operands are referencing the same memory, and where
2051    // OtherPtr may be a bitcast or GEP that currently being rewritten.  (This
2052    // function is only called for mem intrinsics that access the whole
2053    // aggregate, so non-zero GEPs are not an issue here.)
2054    OtherPtr = OtherPtr->stripPointerCasts();
2055
2056    // Copying the alloca to itself is a no-op: just delete it.
2057    if (OtherPtr == AI || OtherPtr == NewElts[0]) {
2058      // This code will run twice for a no-op memcpy -- once for each operand.
2059      // Put only one reference to MI on the DeadInsts list.
2060      for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
2061             E = DeadInsts.end(); I != E; ++I)
2062        if (*I == MI) return;
2063      DeadInsts.push_back(MI);
2064      return;
2065    }
2066
2067    // If the pointer is not the right type, insert a bitcast to the right
2068    // type.
2069    Type *NewTy =
2070      PointerType::get(AI->getType()->getElementType(), AddrSpace);
2071
2072    if (OtherPtr->getType() != NewTy)
2073      OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
2074  }
2075
2076  // Process each element of the aggregate.
2077  bool SROADest = MI->getRawDest() == Inst;
2078
2079  Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
2080
2081  for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2082    // If this is a memcpy/memmove, emit a GEP of the other element address.
2083    Value *OtherElt = 0;
2084    unsigned OtherEltAlign = MemAlignment;
2085
2086    if (OtherPtr) {
2087      Value *Idx[2] = { Zero,
2088                      ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
2089      OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx,
2090                                              OtherPtr->getName()+"."+Twine(i),
2091                                                   MI);
2092      uint64_t EltOffset;
2093      PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
2094      Type *OtherTy = OtherPtrTy->getElementType();
2095      if (StructType *ST = dyn_cast<StructType>(OtherTy)) {
2096        EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
2097      } else {
2098        Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
2099        EltOffset = TD->getTypeAllocSize(EltTy)*i;
2100      }
2101
2102      // The alignment of the other pointer is the guaranteed alignment of the
2103      // element, which is affected by both the known alignment of the whole
2104      // mem intrinsic and the alignment of the element.  If the alignment of
2105      // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
2106      // known alignment is just 4 bytes.
2107      OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
2108    }
2109
2110    Value *EltPtr = NewElts[i];
2111    Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
2112
2113    // If we got down to a scalar, insert a load or store as appropriate.
2114    if (EltTy->isSingleValueType()) {
2115      if (isa<MemTransferInst>(MI)) {
2116        if (SROADest) {
2117          // From Other to Alloca.
2118          Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
2119          new StoreInst(Elt, EltPtr, MI);
2120        } else {
2121          // From Alloca to Other.
2122          Value *Elt = new LoadInst(EltPtr, "tmp", MI);
2123          new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
2124        }
2125        continue;
2126      }
2127      assert(isa<MemSetInst>(MI));
2128
2129      // If the stored element is zero (common case), just store a null
2130      // constant.
2131      Constant *StoreVal;
2132      if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
2133        if (CI->isZero()) {
2134          StoreVal = Constant::getNullValue(EltTy);  // 0.0, null, 0, <0,0>
2135        } else {
2136          // If EltTy is a vector type, get the element type.
2137          Type *ValTy = EltTy->getScalarType();
2138
2139          // Construct an integer with the right value.
2140          unsigned EltSize = TD->getTypeSizeInBits(ValTy);
2141          APInt OneVal(EltSize, CI->getZExtValue());
2142          APInt TotalVal(OneVal);
2143          // Set each byte.
2144          for (unsigned i = 0; 8*i < EltSize; ++i) {
2145            TotalVal = TotalVal.shl(8);
2146            TotalVal |= OneVal;
2147          }
2148
2149          // Convert the integer value to the appropriate type.
2150          StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
2151          if (ValTy->isPointerTy())
2152            StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
2153          else if (ValTy->isFloatingPointTy())
2154            StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
2155          assert(StoreVal->getType() == ValTy && "Type mismatch!");
2156
2157          // If the requested value was a vector constant, create it.
2158          if (EltTy->isVectorTy()) {
2159            unsigned NumElts = cast<VectorType>(EltTy)->getNumElements();
2160            SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
2161            StoreVal = ConstantVector::get(Elts);
2162          }
2163        }
2164        new StoreInst(StoreVal, EltPtr, MI);
2165        continue;
2166      }
2167      // Otherwise, if we're storing a byte variable, use a memset call for
2168      // this element.
2169    }
2170
2171    unsigned EltSize = TD->getTypeAllocSize(EltTy);
2172    if (!EltSize)
2173      continue;
2174
2175    IRBuilder<> Builder(MI);
2176
2177    // Finally, insert the meminst for this element.
2178    if (isa<MemSetInst>(MI)) {
2179      Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
2180                           MI->isVolatile());
2181    } else {
2182      assert(isa<MemTransferInst>(MI));
2183      Value *Dst = SROADest ? EltPtr : OtherElt;  // Dest ptr
2184      Value *Src = SROADest ? OtherElt : EltPtr;  // Src ptr
2185
2186      if (isa<MemCpyInst>(MI))
2187        Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
2188      else
2189        Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
2190    }
2191  }
2192  DeadInsts.push_back(MI);
2193}
2194
2195/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
2196/// overwrites the entire allocation.  Extract out the pieces of the stored
2197/// integer and store them individually.
2198void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
2199                                         SmallVector<AllocaInst*, 32> &NewElts){
2200  // Extract each element out of the integer according to its structure offset
2201  // and store the element value to the individual alloca.
2202  Value *SrcVal = SI->getOperand(0);
2203  Type *AllocaEltTy = AI->getAllocatedType();
2204  uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
2205
2206  IRBuilder<> Builder(SI);
2207
2208  // Handle tail padding by extending the operand
2209  if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
2210    SrcVal = Builder.CreateZExt(SrcVal,
2211                            IntegerType::get(SI->getContext(), AllocaSizeBits));
2212
2213  DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
2214               << '\n');
2215
2216  // There are two forms here: AI could be an array or struct.  Both cases
2217  // have different ways to compute the element offset.
2218  if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2219    const StructLayout *Layout = TD->getStructLayout(EltSTy);
2220
2221    for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2222      // Get the number of bits to shift SrcVal to get the value.
2223      Type *FieldTy = EltSTy->getElementType(i);
2224      uint64_t Shift = Layout->getElementOffsetInBits(i);
2225
2226      if (TD->isBigEndian())
2227        Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
2228
2229      Value *EltVal = SrcVal;
2230      if (Shift) {
2231        Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
2232        EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
2233      }
2234
2235      // Truncate down to an integer of the right size.
2236      uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
2237
2238      // Ignore zero sized fields like {}, they obviously contain no data.
2239      if (FieldSizeBits == 0) continue;
2240
2241      if (FieldSizeBits != AllocaSizeBits)
2242        EltVal = Builder.CreateTrunc(EltVal,
2243                             IntegerType::get(SI->getContext(), FieldSizeBits));
2244      Value *DestField = NewElts[i];
2245      if (EltVal->getType() == FieldTy) {
2246        // Storing to an integer field of this size, just do it.
2247      } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
2248        // Bitcast to the right element type (for fp/vector values).
2249        EltVal = Builder.CreateBitCast(EltVal, FieldTy);
2250      } else {
2251        // Otherwise, bitcast the dest pointer (for aggregates).
2252        DestField = Builder.CreateBitCast(DestField,
2253                                     PointerType::getUnqual(EltVal->getType()));
2254      }
2255      new StoreInst(EltVal, DestField, SI);
2256    }
2257
2258  } else {
2259    ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
2260    Type *ArrayEltTy = ATy->getElementType();
2261    uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
2262    uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
2263
2264    uint64_t Shift;
2265
2266    if (TD->isBigEndian())
2267      Shift = AllocaSizeBits-ElementOffset;
2268    else
2269      Shift = 0;
2270
2271    for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2272      // Ignore zero sized fields like {}, they obviously contain no data.
2273      if (ElementSizeBits == 0) continue;
2274
2275      Value *EltVal = SrcVal;
2276      if (Shift) {
2277        Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
2278        EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
2279      }
2280
2281      // Truncate down to an integer of the right size.
2282      if (ElementSizeBits != AllocaSizeBits)
2283        EltVal = Builder.CreateTrunc(EltVal,
2284                                     IntegerType::get(SI->getContext(),
2285                                                      ElementSizeBits));
2286      Value *DestField = NewElts[i];
2287      if (EltVal->getType() == ArrayEltTy) {
2288        // Storing to an integer field of this size, just do it.
2289      } else if (ArrayEltTy->isFloatingPointTy() ||
2290                 ArrayEltTy->isVectorTy()) {
2291        // Bitcast to the right element type (for fp/vector values).
2292        EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
2293      } else {
2294        // Otherwise, bitcast the dest pointer (for aggregates).
2295        DestField = Builder.CreateBitCast(DestField,
2296                                     PointerType::getUnqual(EltVal->getType()));
2297      }
2298      new StoreInst(EltVal, DestField, SI);
2299
2300      if (TD->isBigEndian())
2301        Shift -= ElementOffset;
2302      else
2303        Shift += ElementOffset;
2304    }
2305  }
2306
2307  DeadInsts.push_back(SI);
2308}
2309
2310/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
2311/// an integer.  Load the individual pieces to form the aggregate value.
2312void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
2313                                        SmallVector<AllocaInst*, 32> &NewElts) {
2314  // Extract each element out of the NewElts according to its structure offset
2315  // and form the result value.
2316  Type *AllocaEltTy = AI->getAllocatedType();
2317  uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
2318
2319  DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
2320               << '\n');
2321
2322  // There are two forms here: AI could be an array or struct.  Both cases
2323  // have different ways to compute the element offset.
2324  const StructLayout *Layout = 0;
2325  uint64_t ArrayEltBitOffset = 0;
2326  if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2327    Layout = TD->getStructLayout(EltSTy);
2328  } else {
2329    Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
2330    ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
2331  }
2332
2333  Value *ResultVal =
2334    Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
2335
2336  for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2337    // Load the value from the alloca.  If the NewElt is an aggregate, cast
2338    // the pointer to an integer of the same size before doing the load.
2339    Value *SrcField = NewElts[i];
2340    Type *FieldTy =
2341      cast<PointerType>(SrcField->getType())->getElementType();
2342    uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
2343
2344    // Ignore zero sized fields like {}, they obviously contain no data.
2345    if (FieldSizeBits == 0) continue;
2346
2347    IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
2348                                                     FieldSizeBits);
2349    if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
2350        !FieldTy->isVectorTy())
2351      SrcField = new BitCastInst(SrcField,
2352                                 PointerType::getUnqual(FieldIntTy),
2353                                 "", LI);
2354    SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
2355
2356    // If SrcField is a fp or vector of the right size but that isn't an
2357    // integer type, bitcast to an integer so we can shift it.
2358    if (SrcField->getType() != FieldIntTy)
2359      SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
2360
2361    // Zero extend the field to be the same size as the final alloca so that
2362    // we can shift and insert it.
2363    if (SrcField->getType() != ResultVal->getType())
2364      SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
2365
2366    // Determine the number of bits to shift SrcField.
2367    uint64_t Shift;
2368    if (Layout) // Struct case.
2369      Shift = Layout->getElementOffsetInBits(i);
2370    else  // Array case.
2371      Shift = i*ArrayEltBitOffset;
2372
2373    if (TD->isBigEndian())
2374      Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
2375
2376    if (Shift) {
2377      Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
2378      SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
2379    }
2380
2381    // Don't create an 'or x, 0' on the first iteration.
2382    if (!isa<Constant>(ResultVal) ||
2383        !cast<Constant>(ResultVal)->isNullValue())
2384      ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
2385    else
2386      ResultVal = SrcField;
2387  }
2388
2389  // Handle tail padding by truncating the result
2390  if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
2391    ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
2392
2393  LI->replaceAllUsesWith(ResultVal);
2394  DeadInsts.push_back(LI);
2395}
2396
2397/// HasPadding - Return true if the specified type has any structure or
2398/// alignment padding in between the elements that would be split apart
2399/// by SROA; return false otherwise.
2400static bool HasPadding(Type *Ty, const TargetData &TD) {
2401  if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2402    Ty = ATy->getElementType();
2403    return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
2404  }
2405
2406  // SROA currently handles only Arrays and Structs.
2407  StructType *STy = cast<StructType>(Ty);
2408  const StructLayout *SL = TD.getStructLayout(STy);
2409  unsigned PrevFieldBitOffset = 0;
2410  for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2411    unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
2412
2413    // Check to see if there is any padding between this element and the
2414    // previous one.
2415    if (i) {
2416      unsigned PrevFieldEnd =
2417        PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
2418      if (PrevFieldEnd < FieldBitOffset)
2419        return true;
2420    }
2421    PrevFieldBitOffset = FieldBitOffset;
2422  }
2423  // Check for tail padding.
2424  if (unsigned EltCount = STy->getNumElements()) {
2425    unsigned PrevFieldEnd = PrevFieldBitOffset +
2426      TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
2427    if (PrevFieldEnd < SL->getSizeInBits())
2428      return true;
2429  }
2430  return false;
2431}
2432
2433/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
2434/// an aggregate can be broken down into elements.  Return 0 if not, 3 if safe,
2435/// or 1 if safe after canonicalization has been performed.
2436bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
2437  // Loop over the use list of the alloca.  We can only transform it if all of
2438  // the users are safe to transform.
2439  AllocaInfo Info(AI);
2440
2441  isSafeForScalarRepl(AI, 0, Info);
2442  if (Info.isUnsafe) {
2443    DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
2444    return false;
2445  }
2446
2447  // Okay, we know all the users are promotable.  If the aggregate is a memcpy
2448  // source and destination, we have to be careful.  In particular, the memcpy
2449  // could be moving around elements that live in structure padding of the LLVM
2450  // types, but may actually be used.  In these cases, we refuse to promote the
2451  // struct.
2452  if (Info.isMemCpySrc && Info.isMemCpyDst &&
2453      HasPadding(AI->getAllocatedType(), *TD))
2454    return false;
2455
2456  // If the alloca never has an access to just *part* of it, but is accessed
2457  // via loads and stores, then we should use ConvertToScalarInfo to promote
2458  // the alloca instead of promoting each piece at a time and inserting fission
2459  // and fusion code.
2460  if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
2461    // If the struct/array just has one element, use basic SRoA.
2462    if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
2463      if (ST->getNumElements() > 1) return false;
2464    } else {
2465      if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
2466        return false;
2467    }
2468  }
2469
2470  return true;
2471}
2472
2473
2474
2475/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
2476/// some part of a constant global variable.  This intentionally only accepts
2477/// constant expressions because we don't can't rewrite arbitrary instructions.
2478static bool PointsToConstantGlobal(Value *V) {
2479  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
2480    return GV->isConstant();
2481  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2482    if (CE->getOpcode() == Instruction::BitCast ||
2483        CE->getOpcode() == Instruction::GetElementPtr)
2484      return PointsToConstantGlobal(CE->getOperand(0));
2485  return false;
2486}
2487
2488/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
2489/// pointer to an alloca.  Ignore any reads of the pointer, return false if we
2490/// see any stores or other unknown uses.  If we see pointer arithmetic, keep
2491/// track of whether it moves the pointer (with isOffset) but otherwise traverse
2492/// the uses.  If we see a memcpy/memmove that targets an unoffseted pointer to
2493/// the alloca, and if the source pointer is a pointer to a constant global, we
2494/// can optimize this.
2495static bool
2496isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
2497                               bool isOffset,
2498                               SmallVector<Instruction *, 4> &LifetimeMarkers) {
2499  // We track lifetime intrinsics as we encounter them.  If we decide to go
2500  // ahead and replace the value with the global, this lets the caller quickly
2501  // eliminate the markers.
2502
2503  for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
2504    User *U = cast<Instruction>(*UI);
2505
2506    if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
2507      // Ignore non-volatile loads, they are always ok.
2508      if (!LI->isSimple()) return false;
2509      continue;
2510    }
2511
2512    if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
2513      // If uses of the bitcast are ok, we are ok.
2514      if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset,
2515                                          LifetimeMarkers))
2516        return false;
2517      continue;
2518    }
2519    if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
2520      // If the GEP has all zero indices, it doesn't offset the pointer.  If it
2521      // doesn't, it does.
2522      if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
2523                                          isOffset || !GEP->hasAllZeroIndices(),
2524                                          LifetimeMarkers))
2525        return false;
2526      continue;
2527    }
2528
2529    if (CallSite CS = U) {
2530      // If this is the function being called then we treat it like a load and
2531      // ignore it.
2532      if (CS.isCallee(UI))
2533        continue;
2534
2535      // If this is a readonly/readnone call site, then we know it is just a
2536      // load (but one that potentially returns the value itself), so we can
2537      // ignore it if we know that the value isn't captured.
2538      unsigned ArgNo = CS.getArgumentNo(UI);
2539      if (CS.onlyReadsMemory() &&
2540          (CS.getInstruction()->use_empty() || CS.doesNotCapture(ArgNo)))
2541        continue;
2542
2543      // If this is being passed as a byval argument, the caller is making a
2544      // copy, so it is only a read of the alloca.
2545      if (CS.isByValArgument(ArgNo))
2546        continue;
2547    }
2548
2549    // Lifetime intrinsics can be handled by the caller.
2550    if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
2551      if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2552          II->getIntrinsicID() == Intrinsic::lifetime_end) {
2553        assert(II->use_empty() && "Lifetime markers have no result to use!");
2554        LifetimeMarkers.push_back(II);
2555        continue;
2556      }
2557    }
2558
2559    // If this is isn't our memcpy/memmove, reject it as something we can't
2560    // handle.
2561    MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
2562    if (MI == 0)
2563      return false;
2564
2565    // If the transfer is using the alloca as a source of the transfer, then
2566    // ignore it since it is a load (unless the transfer is volatile).
2567    if (UI.getOperandNo() == 1) {
2568      if (MI->isVolatile()) return false;
2569      continue;
2570    }
2571
2572    // If we already have seen a copy, reject the second one.
2573    if (TheCopy) return false;
2574
2575    // If the pointer has been offset from the start of the alloca, we can't
2576    // safely handle this.
2577    if (isOffset) return false;
2578
2579    // If the memintrinsic isn't using the alloca as the dest, reject it.
2580    if (UI.getOperandNo() != 0) return false;
2581
2582    // If the source of the memcpy/move is not a constant global, reject it.
2583    if (!PointsToConstantGlobal(MI->getSource()))
2584      return false;
2585
2586    // Otherwise, the transform is safe.  Remember the copy instruction.
2587    TheCopy = MI;
2588  }
2589  return true;
2590}
2591
2592/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
2593/// modified by a copy from a constant global.  If we can prove this, we can
2594/// replace any uses of the alloca with uses of the global directly.
2595MemTransferInst *
2596SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
2597                                     SmallVector<Instruction*, 4> &ToDelete) {
2598  MemTransferInst *TheCopy = 0;
2599  if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false, ToDelete))
2600    return TheCopy;
2601  return 0;
2602}
2603