1193323Sed//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This transformation implements the well known scalar replacement of
11193323Sed// aggregates transformation.  This xform breaks up alloca instructions of
12193323Sed// aggregate type (structure or array) into individual alloca instructions for
13193323Sed// each member (if possible).  Then, if possible, it transforms the individual
14193323Sed// alloca instructions into nice clean scalar SSA form.
15193323Sed//
16235633Sdim// This combines a simple SRoA algorithm with the Mem2Reg algorithm because they
17193323Sed// often interact, especially for C++ programs.  As such, iterating between
18193323Sed// SRoA, then Mem2Reg until we run out of things to promote works well.
19193323Sed//
20193323Sed//===----------------------------------------------------------------------===//
21193323Sed
22193323Sed#define DEBUG_TYPE "scalarrepl"
23193323Sed#include "llvm/Transforms/Scalar.h"
24245431Sdim#include "llvm/ADT/SetVector.h"
25245431Sdim#include "llvm/ADT/SmallVector.h"
26245431Sdim#include "llvm/ADT/Statistic.h"
27193323Sed#include "llvm/Analysis/Dominators.h"
28218893Sdim#include "llvm/Analysis/Loads.h"
29218893Sdim#include "llvm/Analysis/ValueTracking.h"
30252723Sdim#include "llvm/DIBuilder.h"
31252723Sdim#include "llvm/DebugInfo.h"
32252723Sdim#include "llvm/IR/Constants.h"
33252723Sdim#include "llvm/IR/DataLayout.h"
34252723Sdim#include "llvm/IR/DerivedTypes.h"
35252723Sdim#include "llvm/IR/Function.h"
36252723Sdim#include "llvm/IR/GlobalVariable.h"
37252723Sdim#include "llvm/IR/IRBuilder.h"
38252723Sdim#include "llvm/IR/Instructions.h"
39252723Sdim#include "llvm/IR/IntrinsicInst.h"
40252723Sdim#include "llvm/IR/LLVMContext.h"
41252723Sdim#include "llvm/IR/Module.h"
42252723Sdim#include "llvm/IR/Operator.h"
43252723Sdim#include "llvm/Pass.h"
44218893Sdim#include "llvm/Support/CallSite.h"
45193323Sed#include "llvm/Support/Debug.h"
46198090Srdivacky#include "llvm/Support/ErrorHandling.h"
47193323Sed#include "llvm/Support/GetElementPtrTypeIterator.h"
48193323Sed#include "llvm/Support/MathExtras.h"
49198090Srdivacky#include "llvm/Support/raw_ostream.h"
50245431Sdim#include "llvm/Transforms/Utils/Local.h"
51245431Sdim#include "llvm/Transforms/Utils/PromoteMemToReg.h"
52245431Sdim#include "llvm/Transforms/Utils/SSAUpdater.h"
53193323Sedusing namespace llvm;
54193323Sed
55193323SedSTATISTIC(NumReplaced,  "Number of allocas broken up");
56193323SedSTATISTIC(NumPromoted,  "Number of allocas promoted");
57218893SdimSTATISTIC(NumAdjusted,  "Number of scalar allocas adjusted to allow promotion");
58193323SedSTATISTIC(NumConverted, "Number of aggregates converted to scalar");
59193323Sed
60193323Sednamespace {
61198090Srdivacky  struct SROA : public FunctionPass {
62245431Sdim    SROA(int T, bool hasDT, char &ID, int ST, int AT, int SLT)
63218893Sdim      : FunctionPass(ID), HasDomTree(hasDT) {
64193323Sed      if (T == -1)
65193323Sed        SRThreshold = 128;
66193323Sed      else
67193323Sed        SRThreshold = T;
68245431Sdim      if (ST == -1)
69245431Sdim        StructMemberThreshold = 32;
70245431Sdim      else
71245431Sdim        StructMemberThreshold = ST;
72245431Sdim      if (AT == -1)
73245431Sdim        ArrayElementThreshold = 8;
74245431Sdim      else
75245431Sdim        ArrayElementThreshold = AT;
76245431Sdim      if (SLT == -1)
77245431Sdim        // Do not limit the scalar integer load size if no threshold is given.
78245431Sdim        ScalarLoadThreshold = -1;
79245431Sdim      else
80245431Sdim        ScalarLoadThreshold = SLT;
81193323Sed    }
82193323Sed
83193323Sed    bool runOnFunction(Function &F);
84193323Sed
85193323Sed    bool performScalarRepl(Function &F);
86193323Sed    bool performPromotion(Function &F);
87193323Sed
88193323Sed  private:
89218893Sdim    bool HasDomTree;
90245431Sdim    DataLayout *TD;
91218893Sdim
92201360Srdivacky    /// DeadInsts - Keep track of instructions we have made dead, so that
93201360Srdivacky    /// we can remove them after we are done working.
94201360Srdivacky    SmallVector<Value*, 32> DeadInsts;
95201360Srdivacky
96193323Sed    /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
97193323Sed    /// information about the uses.  All these fields are initialized to false
98193323Sed    /// and set to true when something is learned.
99193323Sed    struct AllocaInfo {
100218893Sdim      /// The alloca to promote.
101218893Sdim      AllocaInst *AI;
102245431Sdim
103218893Sdim      /// CheckedPHIs - This is a set of verified PHI nodes, to prevent infinite
104218893Sdim      /// looping and avoid redundant work.
105218893Sdim      SmallPtrSet<PHINode*, 8> CheckedPHIs;
106245431Sdim
107193323Sed      /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
108193323Sed      bool isUnsafe : 1;
109218893Sdim
110193323Sed      /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
111193323Sed      bool isMemCpySrc : 1;
112193323Sed
113193323Sed      /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
114193323Sed      bool isMemCpyDst : 1;
115193323Sed
116218893Sdim      /// hasSubelementAccess - This is true if a subelement of the alloca is
117218893Sdim      /// ever accessed, or false if the alloca is only accessed with mem
118218893Sdim      /// intrinsics or load/store that only access the entire alloca at once.
119218893Sdim      bool hasSubelementAccess : 1;
120245431Sdim
121218893Sdim      /// hasALoadOrStore - This is true if there are any loads or stores to it.
122218893Sdim      /// The alloca may just be accessed with memcpy, for example, which would
123218893Sdim      /// not set this.
124218893Sdim      bool hasALoadOrStore : 1;
125245431Sdim
126218893Sdim      explicit AllocaInfo(AllocaInst *ai)
127218893Sdim        : AI(ai), isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
128218893Sdim          hasSubelementAccess(false), hasALoadOrStore(false) {}
129193323Sed    };
130218893Sdim
131245431Sdim    /// SRThreshold - The maximum alloca size to considered for SROA.
132193323Sed    unsigned SRThreshold;
133193323Sed
134245431Sdim    /// StructMemberThreshold - The maximum number of members a struct can
135245431Sdim    /// contain to be considered for SROA.
136245431Sdim    unsigned StructMemberThreshold;
137245431Sdim
138245431Sdim    /// ArrayElementThreshold - The maximum number of elements an array can
139245431Sdim    /// have to be considered for SROA.
140245431Sdim    unsigned ArrayElementThreshold;
141245431Sdim
142245431Sdim    /// ScalarLoadThreshold - The maximum size in bits of scalars to load when
143245431Sdim    /// converting to scalar
144245431Sdim    unsigned ScalarLoadThreshold;
145245431Sdim
146218893Sdim    void MarkUnsafe(AllocaInfo &I, Instruction *User) {
147218893Sdim      I.isUnsafe = true;
148218893Sdim      DEBUG(dbgs() << "  Transformation preventing inst: " << *User << '\n');
149218893Sdim    }
150193323Sed
151202878Srdivacky    bool isSafeAllocaToScalarRepl(AllocaInst *AI);
152193323Sed
153218893Sdim    void isSafeForScalarRepl(Instruction *I, uint64_t Offset, AllocaInfo &Info);
154218893Sdim    void isSafePHISelectUseForScalarRepl(Instruction *User, uint64_t Offset,
155218893Sdim                                         AllocaInfo &Info);
156218893Sdim    void isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset, AllocaInfo &Info);
157218893Sdim    void isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
158226890Sdim                         Type *MemOpType, bool isStore, AllocaInfo &Info,
159218893Sdim                         Instruction *TheAccess, bool AllowWholeAccess);
160226890Sdim    bool TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size);
161226890Sdim    uint64_t FindElementAndOffset(Type *&T, uint64_t &Offset,
162226890Sdim                                  Type *&IdxTy);
163218893Sdim
164218893Sdim    void DoScalarReplacement(AllocaInst *AI,
165198892Srdivacky                             std::vector<AllocaInst*> &WorkList);
166201360Srdivacky    void DeleteDeadInstructions();
167218893Sdim
168201360Srdivacky    void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
169263509Sdim                              SmallVectorImpl<AllocaInst *> &NewElts);
170201360Srdivacky    void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
171263509Sdim                        SmallVectorImpl<AllocaInst *> &NewElts);
172201360Srdivacky    void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
173263509Sdim                    SmallVectorImpl<AllocaInst *> &NewElts);
174226890Sdim    void RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
175226890Sdim                                  uint64_t Offset,
176263509Sdim                                  SmallVectorImpl<AllocaInst *> &NewElts);
177201360Srdivacky    void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
178198892Srdivacky                                      AllocaInst *AI,
179263509Sdim                                      SmallVectorImpl<AllocaInst *> &NewElts);
180198892Srdivacky    void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
181263509Sdim                                       SmallVectorImpl<AllocaInst *> &NewElts);
182198892Srdivacky    void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
183263509Sdim                                      SmallVectorImpl<AllocaInst *> &NewElts);
184245431Sdim    bool ShouldAttemptScalarRepl(AllocaInst *AI);
185245431Sdim  };
186218893Sdim
187218893Sdim  // SROA_DT - SROA that uses DominatorTree.
188218893Sdim  struct SROA_DT : public SROA {
189218893Sdim    static char ID;
190218893Sdim  public:
191245431Sdim    SROA_DT(int T = -1, int ST = -1, int AT = -1, int SLT = -1) :
192245431Sdim        SROA(T, true, ID, ST, AT, SLT) {
193218893Sdim      initializeSROA_DTPass(*PassRegistry::getPassRegistry());
194218893Sdim    }
195245431Sdim
196218893Sdim    // getAnalysisUsage - This pass does not require any passes, but we know it
197218893Sdim    // will not alter the CFG, so say so.
198218893Sdim    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
199218893Sdim      AU.addRequired<DominatorTree>();
200218893Sdim      AU.setPreservesCFG();
201218893Sdim    }
202218893Sdim  };
203245431Sdim
204218893Sdim  // SROA_SSAUp - SROA that uses SSAUpdater.
205218893Sdim  struct SROA_SSAUp : public SROA {
206218893Sdim    static char ID;
207218893Sdim  public:
208245431Sdim    SROA_SSAUp(int T = -1, int ST = -1, int AT = -1, int SLT = -1) :
209245431Sdim        SROA(T, false, ID, ST, AT, SLT) {
210218893Sdim      initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
211218893Sdim    }
212245431Sdim
213218893Sdim    // getAnalysisUsage - This pass does not require any passes, but we know it
214218893Sdim    // will not alter the CFG, so say so.
215218893Sdim    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
216218893Sdim      AU.setPreservesCFG();
217218893Sdim    }
218218893Sdim  };
219245431Sdim
220193323Sed}
221193323Sed
222218893Sdimchar SROA_DT::ID = 0;
223218893Sdimchar SROA_SSAUp::ID = 0;
224193323Sed
225218893SdimINITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl",
226218893Sdim                "Scalar Replacement of Aggregates (DT)", false, false)
227218893SdimINITIALIZE_PASS_DEPENDENCY(DominatorTree)
228218893SdimINITIALIZE_PASS_END(SROA_DT, "scalarrepl",
229218893Sdim                "Scalar Replacement of Aggregates (DT)", false, false)
230218893Sdim
231218893SdimINITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
232218893Sdim                      "Scalar Replacement of Aggregates (SSAUp)", false, false)
233218893SdimINITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
234218893Sdim                    "Scalar Replacement of Aggregates (SSAUp)", false, false)
235218893Sdim
236193323Sed// Public interface to the ScalarReplAggregates pass
237218893SdimFunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
238245431Sdim                                                   bool UseDomTree,
239245431Sdim                                                   int StructMemberThreshold,
240245431Sdim                                                   int ArrayElementThreshold,
241245431Sdim                                                   int ScalarLoadThreshold) {
242218893Sdim  if (UseDomTree)
243245431Sdim    return new SROA_DT(Threshold, StructMemberThreshold, ArrayElementThreshold,
244245431Sdim                       ScalarLoadThreshold);
245245431Sdim  return new SROA_SSAUp(Threshold, StructMemberThreshold,
246245431Sdim                        ArrayElementThreshold, ScalarLoadThreshold);
247193323Sed}
248193323Sed
249193323Sed
250207618Srdivacky//===----------------------------------------------------------------------===//
251207618Srdivacky// Convert To Scalar Optimization.
252207618Srdivacky//===----------------------------------------------------------------------===//
253207618Srdivacky
254207618Srdivackynamespace {
255207618Srdivacky/// ConvertToScalarInfo - This class implements the "Convert To Scalar"
256207618Srdivacky/// optimization, which scans the uses of an alloca and determines if it can
257207618Srdivacky/// rewrite it in terms of a single new alloca that can be mem2reg'd.
258207618Srdivackyclass ConvertToScalarInfo {
259221345Sdim  /// AllocaSize - The size of the alloca being considered in bytes.
260207618Srdivacky  unsigned AllocaSize;
261245431Sdim  const DataLayout &TD;
262245431Sdim  unsigned ScalarLoadThreshold;
263218893Sdim
264207618Srdivacky  /// IsNotTrivial - This is set to true if there is some access to the object
265207618Srdivacky  /// which means that mem2reg can't promote it.
266207618Srdivacky  bool IsNotTrivial;
267218893Sdim
268224145Sdim  /// ScalarKind - Tracks the kind of alloca being considered for promotion,
269224145Sdim  /// computed based on the uses of the alloca rather than the LLVM type system.
270224145Sdim  enum {
271224145Sdim    Unknown,
272224145Sdim
273224145Sdim    // Accesses via GEPs that are consistent with element access of a vector
274224145Sdim    // type. This will not be converted into a vector unless there is a later
275224145Sdim    // access using an actual vector type.
276224145Sdim    ImplicitVector,
277224145Sdim
278224145Sdim    // Accesses via vector operations and GEPs that are consistent with the
279224145Sdim    // layout of a vector type.
280224145Sdim    Vector,
281224145Sdim
282224145Sdim    // An integer bag-of-bits with bitwise operations for insertion and
283224145Sdim    // extraction. Any combination of types can be converted into this kind
284224145Sdim    // of scalar.
285224145Sdim    Integer
286224145Sdim  } ScalarKind;
287224145Sdim
288207618Srdivacky  /// VectorTy - This tracks the type that we should promote the vector to if
289207618Srdivacky  /// it is possible to turn it into a vector.  This starts out null, and if it
290207618Srdivacky  /// isn't possible to turn into a vector type, it gets set to VoidTy.
291226890Sdim  VectorType *VectorTy;
292218893Sdim
293245431Sdim  /// HadNonMemTransferAccess - True if there is at least one access to the
294221345Sdim  /// alloca that is not a MemTransferInst.  We don't want to turn structs into
295221345Sdim  /// large integers unless there is some potential for optimization.
296221345Sdim  bool HadNonMemTransferAccess;
297221345Sdim
298245431Sdim  /// HadDynamicAccess - True if some element of this alloca was dynamic.
299245431Sdim  /// We don't yet have support for turning a dynamic access into a large
300245431Sdim  /// integer.
301245431Sdim  bool HadDynamicAccess;
302245431Sdim
303207618Srdivackypublic:
304245431Sdim  explicit ConvertToScalarInfo(unsigned Size, const DataLayout &td,
305245431Sdim                               unsigned SLT)
306245431Sdim    : AllocaSize(Size), TD(td), ScalarLoadThreshold(SLT), IsNotTrivial(false),
307245431Sdim    ScalarKind(Unknown), VectorTy(0), HadNonMemTransferAccess(false),
308245431Sdim    HadDynamicAccess(false) { }
309218893Sdim
310207618Srdivacky  AllocaInst *TryConvert(AllocaInst *AI);
311218893Sdim
312207618Srdivackyprivate:
313245431Sdim  bool CanConvertToScalar(Value *V, uint64_t Offset, Value* NonConstantIdx);
314226890Sdim  void MergeInTypeForLoadOrStore(Type *In, uint64_t Offset);
315226890Sdim  bool MergeInVectorType(VectorType *VInTy, uint64_t Offset);
316245431Sdim  void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset,
317245431Sdim                           Value *NonConstantIdx);
318218893Sdim
319226890Sdim  Value *ConvertScalar_ExtractValue(Value *NV, Type *ToType,
320245431Sdim                                    uint64_t Offset, Value* NonConstantIdx,
321245431Sdim                                    IRBuilder<> &Builder);
322207618Srdivacky  Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
323245431Sdim                                   uint64_t Offset, Value* NonConstantIdx,
324245431Sdim                                   IRBuilder<> &Builder);
325207618Srdivacky};
326207618Srdivacky} // end anonymous namespace.
327207618Srdivacky
328212904Sdim
329207618Srdivacky/// TryConvert - Analyze the specified alloca, and if it is safe to do so,
330207618Srdivacky/// rewrite it to be a new alloca which is mem2reg'able.  This returns the new
331207618Srdivacky/// alloca if possible or null if not.
332207618SrdivackyAllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
333207618Srdivacky  // If we can't convert this scalar, or if mem2reg can trivially do it, bail
334207618Srdivacky  // out.
335245431Sdim  if (!CanConvertToScalar(AI, 0, 0) || !IsNotTrivial)
336207618Srdivacky    return 0;
337218893Sdim
338224145Sdim  // If an alloca has only memset / memcpy uses, it may still have an Unknown
339224145Sdim  // ScalarKind. Treat it as an Integer below.
340224145Sdim  if (ScalarKind == Unknown)
341224145Sdim    ScalarKind = Integer;
342224145Sdim
343224145Sdim  if (ScalarKind == Vector && VectorTy->getBitWidth() != AllocaSize * 8)
344224145Sdim    ScalarKind = Integer;
345224145Sdim
346207618Srdivacky  // If we were able to find a vector type that can handle this with
347207618Srdivacky  // insert/extract elements, and if there was at least one use that had
348207618Srdivacky  // a vector type, promote this to a vector.  We don't want to promote
349207618Srdivacky  // random stuff that doesn't use vectors (e.g. <9 x double>) because then
350207618Srdivacky  // we just get a lot of insert/extracts.  If at least one vector is
351207618Srdivacky  // involved, then we probably really do have a union of vector/array.
352226890Sdim  Type *NewTy;
353224145Sdim  if (ScalarKind == Vector) {
354224145Sdim    assert(VectorTy && "Missing type for vector scalar.");
355207618Srdivacky    DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n  TYPE = "
356207618Srdivacky          << *VectorTy << '\n');
357207618Srdivacky    NewTy = VectorTy;  // Use the vector type.
358207618Srdivacky  } else {
359221345Sdim    unsigned BitWidth = AllocaSize * 8;
360245431Sdim
361245431Sdim    // Do not convert to scalar integer if the alloca size exceeds the
362245431Sdim    // scalar load threshold.
363245431Sdim    if (BitWidth > ScalarLoadThreshold)
364245431Sdim      return 0;
365245431Sdim
366224145Sdim    if ((ScalarKind == ImplicitVector || ScalarKind == Integer) &&
367224145Sdim        !HadNonMemTransferAccess && !TD.fitsInLegalInteger(BitWidth))
368221345Sdim      return 0;
369245431Sdim    // Dynamic accesses on integers aren't yet supported.  They need us to shift
370245431Sdim    // by a dynamic amount which could be difficult to work out as we might not
371245431Sdim    // know whether to use a left or right shift.
372245431Sdim    if (ScalarKind == Integer && HadDynamicAccess)
373245431Sdim      return 0;
374221345Sdim
375207618Srdivacky    DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
376207618Srdivacky    // Create and insert the integer alloca.
377221345Sdim    NewTy = IntegerType::get(AI->getContext(), BitWidth);
378207618Srdivacky  }
379207618Srdivacky  AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
380245431Sdim  ConvertUsesToScalar(AI, NewAI, 0, 0);
381207618Srdivacky  return NewAI;
382207618Srdivacky}
383207618Srdivacky
384224145Sdim/// MergeInTypeForLoadOrStore - Add the 'In' type to the accumulated vector type
385224145Sdim/// (VectorTy) so far at the offset specified by Offset (which is specified in
386224145Sdim/// bytes).
387207618Srdivacky///
388226890Sdim/// There are two cases we handle here:
389207618Srdivacky///   1) A union of vector types of the same size and potentially its elements.
390207618Srdivacky///      Here we turn element accesses into insert/extract element operations.
391207618Srdivacky///      This promotes a <4 x float> with a store of float to the third element
392207618Srdivacky///      into a <4 x float> that uses insert element.
393226890Sdim///   2) A fully general blob of memory, which we turn into some (potentially
394207618Srdivacky///      large) integer type with extract and insert operations where the loads
395207618Srdivacky///      and stores would mutate the memory.  We mark this by setting VectorTy
396207618Srdivacky///      to VoidTy.
397226890Sdimvoid ConvertToScalarInfo::MergeInTypeForLoadOrStore(Type *In,
398224145Sdim                                                    uint64_t Offset) {
399207618Srdivacky  // If we already decided to turn this into a blob of integer memory, there is
400207618Srdivacky  // nothing to be done.
401224145Sdim  if (ScalarKind == Integer)
402207618Srdivacky    return;
403218893Sdim
404207618Srdivacky  // If this could be contributing to a vector, analyze it.
405207618Srdivacky
406207618Srdivacky  // If the In type is a vector that is the same size as the alloca, see if it
407207618Srdivacky  // matches the existing VecTy.
408226890Sdim  if (VectorType *VInTy = dyn_cast<VectorType>(In)) {
409221345Sdim    if (MergeInVectorType(VInTy, Offset))
410207618Srdivacky      return;
411207618Srdivacky  } else if (In->isFloatTy() || In->isDoubleTy() ||
412207618Srdivacky             (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
413207618Srdivacky              isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
414221345Sdim    // Full width accesses can be ignored, because they can always be turned
415221345Sdim    // into bitcasts.
416221345Sdim    unsigned EltSize = In->getPrimitiveSizeInBits()/8;
417224145Sdim    if (EltSize == AllocaSize)
418221345Sdim      return;
419221345Sdim
420207618Srdivacky    // If we're accessing something that could be an element of a vector, see
421207618Srdivacky    // if the implied vector agrees with what we already have and if Offset is
422207618Srdivacky    // compatible with it.
423223017Sdim    if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
424226890Sdim        (!VectorTy || EltSize == VectorTy->getElementType()
425226890Sdim                                         ->getPrimitiveSizeInBits()/8)) {
426221345Sdim      if (!VectorTy) {
427224145Sdim        ScalarKind = ImplicitVector;
428207618Srdivacky        VectorTy = VectorType::get(In, AllocaSize/EltSize);
429221345Sdim      }
430226890Sdim      return;
431207618Srdivacky    }
432207618Srdivacky  }
433218893Sdim
434207618Srdivacky  // Otherwise, we have a case that we can't handle with an optimized vector
435207618Srdivacky  // form.  We can still turn this into a large integer.
436224145Sdim  ScalarKind = Integer;
437207618Srdivacky}
438207618Srdivacky
439224145Sdim/// MergeInVectorType - Handles the vector case of MergeInTypeForLoadOrStore,
440224145Sdim/// returning true if the type was successfully merged and false otherwise.
441226890Sdimbool ConvertToScalarInfo::MergeInVectorType(VectorType *VInTy,
442221345Sdim                                            uint64_t Offset) {
443226890Sdim  if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
444226890Sdim    // If we're storing/loading a vector of the right size, allow it as a
445226890Sdim    // vector.  If this the first vector we see, remember the type so that
446226890Sdim    // we know the element size. If this is a subsequent access, ignore it
447226890Sdim    // even if it is a differing type but the same size. Worst case we can
448226890Sdim    // bitcast the resultant vectors.
449226890Sdim    if (!VectorTy)
450226890Sdim      VectorTy = VInTy;
451224145Sdim    ScalarKind = Vector;
452221345Sdim    return true;
453221345Sdim  }
454221345Sdim
455226890Sdim  return false;
456221345Sdim}
457221345Sdim
458207618Srdivacky/// CanConvertToScalar - V is a pointer.  If we can convert the pointee and all
459207618Srdivacky/// its accesses to a single vector type, return true and set VecTy to
460207618Srdivacky/// the new type.  If we could convert the alloca into a single promotable
461207618Srdivacky/// integer, return true but set VecTy to VoidTy.  Further, if the use is not a
462207618Srdivacky/// completely trivial use that mem2reg could promote, set IsNotTrivial.  Offset
463207618Srdivacky/// is the current offset from the base of the alloca being analyzed.
464207618Srdivacky///
465207618Srdivacky/// If we see at least one access to the value that is as a vector type, set the
466207618Srdivacky/// SawVec flag.
467245431Sdimbool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset,
468245431Sdim                                             Value* NonConstantIdx) {
469207618Srdivacky  for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
470207618Srdivacky    Instruction *User = cast<Instruction>(*UI);
471218893Sdim
472207618Srdivacky    if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
473207618Srdivacky      // Don't break volatile loads.
474226890Sdim      if (!LI->isSimple())
475207618Srdivacky        return false;
476218893Sdim      // Don't touch MMX operations.
477218893Sdim      if (LI->getType()->isX86_MMXTy())
478218893Sdim        return false;
479221345Sdim      HadNonMemTransferAccess = true;
480224145Sdim      MergeInTypeForLoadOrStore(LI->getType(), Offset);
481207618Srdivacky      continue;
482207618Srdivacky    }
483218893Sdim
484207618Srdivacky    if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
485207618Srdivacky      // Storing the pointer, not into the value?
486226890Sdim      if (SI->getOperand(0) == V || !SI->isSimple()) return false;
487218893Sdim      // Don't touch MMX operations.
488218893Sdim      if (SI->getOperand(0)->getType()->isX86_MMXTy())
489218893Sdim        return false;
490221345Sdim      HadNonMemTransferAccess = true;
491224145Sdim      MergeInTypeForLoadOrStore(SI->getOperand(0)->getType(), Offset);
492207618Srdivacky      continue;
493207618Srdivacky    }
494218893Sdim
495207618Srdivacky    if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
496226890Sdim      if (!onlyUsedByLifetimeMarkers(BCI))
497226890Sdim        IsNotTrivial = true;  // Can't be mem2reg'd.
498245431Sdim      if (!CanConvertToScalar(BCI, Offset, NonConstantIdx))
499207618Srdivacky        return false;
500207618Srdivacky      continue;
501207618Srdivacky    }
502207618Srdivacky
503207618Srdivacky    if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
504207618Srdivacky      // If this is a GEP with a variable indices, we can't handle it.
505245431Sdim      PointerType* PtrTy = dyn_cast<PointerType>(GEP->getPointerOperandType());
506245431Sdim      if (!PtrTy)
507207618Srdivacky        return false;
508218893Sdim
509207618Srdivacky      // Compute the offset that this GEP adds to the pointer.
510207618Srdivacky      SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
511245431Sdim      Value *GEPNonConstantIdx = 0;
512245431Sdim      if (!GEP->hasAllConstantIndices()) {
513245431Sdim        if (!isa<VectorType>(PtrTy->getElementType()))
514245431Sdim          return false;
515245431Sdim        if (NonConstantIdx)
516245431Sdim          return false;
517245431Sdim        GEPNonConstantIdx = Indices.pop_back_val();
518245431Sdim        if (!GEPNonConstantIdx->getType()->isIntegerTy(32))
519245431Sdim          return false;
520245431Sdim        HadDynamicAccess = true;
521245431Sdim      } else
522245431Sdim        GEPNonConstantIdx = NonConstantIdx;
523245431Sdim      uint64_t GEPOffset = TD.getIndexedOffset(PtrTy,
524226890Sdim                                               Indices);
525207618Srdivacky      // See if all uses can be converted.
526245431Sdim      if (!CanConvertToScalar(GEP, Offset+GEPOffset, GEPNonConstantIdx))
527207618Srdivacky        return false;
528207618Srdivacky      IsNotTrivial = true;  // Can't be mem2reg'd.
529221345Sdim      HadNonMemTransferAccess = true;
530207618Srdivacky      continue;
531207618Srdivacky    }
532207618Srdivacky
533207618Srdivacky    // If this is a constant sized memset of a constant value (e.g. 0) we can
534207618Srdivacky    // handle it.
535207618Srdivacky    if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
536245431Sdim      // Store to dynamic index.
537245431Sdim      if (NonConstantIdx)
538245431Sdim        return false;
539224145Sdim      // Store of constant value.
540224145Sdim      if (!isa<ConstantInt>(MSI->getValue()))
541207618Srdivacky        return false;
542224145Sdim
543224145Sdim      // Store of constant size.
544224145Sdim      ConstantInt *Len = dyn_cast<ConstantInt>(MSI->getLength());
545224145Sdim      if (!Len)
546224145Sdim        return false;
547224145Sdim
548224145Sdim      // If the size differs from the alloca, we can only convert the alloca to
549224145Sdim      // an integer bag-of-bits.
550224145Sdim      // FIXME: This should handle all of the cases that are currently accepted
551224145Sdim      // as vector element insertions.
552224145Sdim      if (Len->getZExtValue() != AllocaSize || Offset != 0)
553224145Sdim        ScalarKind = Integer;
554224145Sdim
555207618Srdivacky      IsNotTrivial = true;  // Can't be mem2reg'd.
556221345Sdim      HadNonMemTransferAccess = true;
557207618Srdivacky      continue;
558207618Srdivacky    }
559207618Srdivacky
560207618Srdivacky    // If this is a memcpy or memmove into or out of the whole allocation, we
561207618Srdivacky    // can handle it like a load or store of the scalar type.
562207618Srdivacky    if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
563245431Sdim      // Store to dynamic index.
564245431Sdim      if (NonConstantIdx)
565245431Sdim        return false;
566207618Srdivacky      ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
567207618Srdivacky      if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
568207618Srdivacky        return false;
569218893Sdim
570207618Srdivacky      IsNotTrivial = true;  // Can't be mem2reg'd.
571207618Srdivacky      continue;
572207618Srdivacky    }
573218893Sdim
574226890Sdim    // If this is a lifetime intrinsic, we can handle it.
575226890Sdim    if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
576226890Sdim      if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
577226890Sdim          II->getIntrinsicID() == Intrinsic::lifetime_end) {
578226890Sdim        continue;
579226890Sdim      }
580226890Sdim    }
581226890Sdim
582207618Srdivacky    // Otherwise, we cannot handle this!
583207618Srdivacky    return false;
584207618Srdivacky  }
585218893Sdim
586207618Srdivacky  return true;
587207618Srdivacky}
588207618Srdivacky
589207618Srdivacky/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
590207618Srdivacky/// directly.  This happens when we are converting an "integer union" to a
591207618Srdivacky/// single integer scalar, or when we are converting a "vector union" to a
592207618Srdivacky/// vector with insert/extractelement instructions.
593207618Srdivacky///
594207618Srdivacky/// Offset is an offset from the original alloca, in bits that need to be
595207618Srdivacky/// shifted to the right.  By the end of this, there should be no uses of Ptr.
596207618Srdivackyvoid ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
597245431Sdim                                              uint64_t Offset,
598245431Sdim                                              Value* NonConstantIdx) {
599207618Srdivacky  while (!Ptr->use_empty()) {
600207618Srdivacky    Instruction *User = cast<Instruction>(Ptr->use_back());
601207618Srdivacky
602207618Srdivacky    if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
603245431Sdim      ConvertUsesToScalar(CI, NewAI, Offset, NonConstantIdx);
604207618Srdivacky      CI->eraseFromParent();
605207618Srdivacky      continue;
606207618Srdivacky    }
607207618Srdivacky
608207618Srdivacky    if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
609207618Srdivacky      // Compute the offset that this GEP adds to the pointer.
610207618Srdivacky      SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
611245431Sdim      Value* GEPNonConstantIdx = 0;
612245431Sdim      if (!GEP->hasAllConstantIndices()) {
613245431Sdim        assert(!NonConstantIdx &&
614245431Sdim               "Dynamic GEP reading from dynamic GEP unsupported");
615245431Sdim        GEPNonConstantIdx = Indices.pop_back_val();
616245431Sdim      } else
617245431Sdim        GEPNonConstantIdx = NonConstantIdx;
618207618Srdivacky      uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
619226890Sdim                                               Indices);
620245431Sdim      ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8, GEPNonConstantIdx);
621207618Srdivacky      GEP->eraseFromParent();
622207618Srdivacky      continue;
623207618Srdivacky    }
624218893Sdim
625218893Sdim    IRBuilder<> Builder(User);
626218893Sdim
627207618Srdivacky    if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
628207618Srdivacky      // The load is a bit extract from NewAI shifted right by Offset bits.
629226890Sdim      Value *LoadedVal = Builder.CreateLoad(NewAI);
630207618Srdivacky      Value *NewLoadVal
631245431Sdim        = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset,
632245431Sdim                                     NonConstantIdx, Builder);
633207618Srdivacky      LI->replaceAllUsesWith(NewLoadVal);
634207618Srdivacky      LI->eraseFromParent();
635207618Srdivacky      continue;
636207618Srdivacky    }
637218893Sdim
638207618Srdivacky    if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
639207618Srdivacky      assert(SI->getOperand(0) != Ptr && "Consistency error!");
640207618Srdivacky      Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
641207618Srdivacky      Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
642245431Sdim                                             NonConstantIdx, Builder);
643207618Srdivacky      Builder.CreateStore(New, NewAI);
644207618Srdivacky      SI->eraseFromParent();
645218893Sdim
646207618Srdivacky      // If the load we just inserted is now dead, then the inserted store
647207618Srdivacky      // overwrote the entire thing.
648207618Srdivacky      if (Old->use_empty())
649207618Srdivacky        Old->eraseFromParent();
650207618Srdivacky      continue;
651207618Srdivacky    }
652218893Sdim
653207618Srdivacky    // If this is a constant sized memset of a constant value (e.g. 0) we can
654207618Srdivacky    // transform it into a store of the expanded constant value.
655207618Srdivacky    if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
656207618Srdivacky      assert(MSI->getRawDest() == Ptr && "Consistency error!");
657245431Sdim      assert(!NonConstantIdx && "Cannot replace dynamic memset with insert");
658235633Sdim      int64_t SNumBytes = cast<ConstantInt>(MSI->getLength())->getSExtValue();
659235633Sdim      if (SNumBytes > 0 && (SNumBytes >> 32) == 0) {
660235633Sdim        unsigned NumBytes = static_cast<unsigned>(SNumBytes);
661207618Srdivacky        unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
662218893Sdim
663207618Srdivacky        // Compute the value replicated the right number of times.
664207618Srdivacky        APInt APVal(NumBytes*8, Val);
665207618Srdivacky
666207618Srdivacky        // Splat the value if non-zero.
667207618Srdivacky        if (Val)
668207618Srdivacky          for (unsigned i = 1; i != NumBytes; ++i)
669207618Srdivacky            APVal |= APVal << 8;
670218893Sdim
671207618Srdivacky        Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
672207618Srdivacky        Value *New = ConvertScalar_InsertValue(
673207618Srdivacky                                    ConstantInt::get(User->getContext(), APVal),
674245431Sdim                                               Old, Offset, 0, Builder);
675207618Srdivacky        Builder.CreateStore(New, NewAI);
676218893Sdim
677207618Srdivacky        // If the load we just inserted is now dead, then the memset overwrote
678207618Srdivacky        // the entire thing.
679207618Srdivacky        if (Old->use_empty())
680218893Sdim          Old->eraseFromParent();
681207618Srdivacky      }
682207618Srdivacky      MSI->eraseFromParent();
683207618Srdivacky      continue;
684207618Srdivacky    }
685207618Srdivacky
686207618Srdivacky    // If this is a memcpy or memmove into or out of the whole allocation, we
687207618Srdivacky    // can handle it like a load or store of the scalar type.
688207618Srdivacky    if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
689207618Srdivacky      assert(Offset == 0 && "must be store to start of alloca");
690245431Sdim      assert(!NonConstantIdx && "Cannot replace dynamic transfer with insert");
691218893Sdim
692207618Srdivacky      // If the source and destination are both to the same alloca, then this is
693207618Srdivacky      // a noop copy-to-self, just delete it.  Otherwise, emit a load and store
694207618Srdivacky      // as appropriate.
695218893Sdim      AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, &TD, 0));
696218893Sdim
697218893Sdim      if (GetUnderlyingObject(MTI->getSource(), &TD, 0) != OrigAI) {
698207618Srdivacky        // Dest must be OrigAI, change this to be a load from the original
699207618Srdivacky        // pointer (bitcasted), then a store to our new alloca.
700207618Srdivacky        assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
701207618Srdivacky        Value *SrcPtr = MTI->getSource();
702226890Sdim        PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
703226890Sdim        PointerType* AIPTy = cast<PointerType>(NewAI->getType());
704218893Sdim        if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
705218893Sdim          AIPTy = PointerType::get(AIPTy->getElementType(),
706218893Sdim                                   SPTy->getAddressSpace());
707218893Sdim        }
708218893Sdim        SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
709218893Sdim
710207618Srdivacky        LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
711207618Srdivacky        SrcVal->setAlignment(MTI->getAlignment());
712207618Srdivacky        Builder.CreateStore(SrcVal, NewAI);
713218893Sdim      } else if (GetUnderlyingObject(MTI->getDest(), &TD, 0) != OrigAI) {
714207618Srdivacky        // Src must be OrigAI, change this to be a load from NewAI then a store
715207618Srdivacky        // through the original dest pointer (bitcasted).
716207618Srdivacky        assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
717207618Srdivacky        LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
718207618Srdivacky
719226890Sdim        PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
720226890Sdim        PointerType* AIPTy = cast<PointerType>(NewAI->getType());
721218893Sdim        if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
722218893Sdim          AIPTy = PointerType::get(AIPTy->getElementType(),
723218893Sdim                                   DPTy->getAddressSpace());
724218893Sdim        }
725218893Sdim        Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
726218893Sdim
727207618Srdivacky        StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
728207618Srdivacky        NewStore->setAlignment(MTI->getAlignment());
729207618Srdivacky      } else {
730207618Srdivacky        // Noop transfer. Src == Dst
731207618Srdivacky      }
732207618Srdivacky
733207618Srdivacky      MTI->eraseFromParent();
734207618Srdivacky      continue;
735207618Srdivacky    }
736218893Sdim
737226890Sdim    if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
738226890Sdim      if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
739226890Sdim          II->getIntrinsicID() == Intrinsic::lifetime_end) {
740226890Sdim        // There's no need to preserve these, as the resulting alloca will be
741226890Sdim        // converted to a register anyways.
742226890Sdim        II->eraseFromParent();
743226890Sdim        continue;
744226890Sdim      }
745226890Sdim    }
746226890Sdim
747207618Srdivacky    llvm_unreachable("Unsupported operation!");
748207618Srdivacky  }
749207618Srdivacky}
750207618Srdivacky
751207618Srdivacky/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
752207618Srdivacky/// or vector value FromVal, extracting the bits from the offset specified by
753207618Srdivacky/// Offset.  This returns the value, which is of type ToType.
754207618Srdivacky///
755207618Srdivacky/// This happens when we are converting an "integer union" to a single
756207618Srdivacky/// integer scalar, or when we are converting a "vector union" to a vector with
757207618Srdivacky/// insert/extractelement instructions.
758207618Srdivacky///
759207618Srdivacky/// Offset is an offset from the original alloca, in bits that need to be
760207618Srdivacky/// shifted to the right.
761207618SrdivackyValue *ConvertToScalarInfo::
762226890SdimConvertScalar_ExtractValue(Value *FromVal, Type *ToType,
763245431Sdim                           uint64_t Offset, Value* NonConstantIdx,
764245431Sdim                           IRBuilder<> &Builder) {
765207618Srdivacky  // If the load is of the whole new alloca, no conversion is needed.
766226890Sdim  Type *FromType = FromVal->getType();
767221345Sdim  if (FromType == ToType && Offset == 0)
768207618Srdivacky    return FromVal;
769207618Srdivacky
770207618Srdivacky  // If the result alloca is a vector type, this is either an element
771207618Srdivacky  // access or a bitcast to another vector type of the same size.
772226890Sdim  if (VectorType *VTy = dyn_cast<VectorType>(FromType)) {
773223017Sdim    unsigned FromTypeSize = TD.getTypeAllocSize(FromType);
774221345Sdim    unsigned ToTypeSize = TD.getTypeAllocSize(ToType);
775226890Sdim    if (FromTypeSize == ToTypeSize)
776226890Sdim        return Builder.CreateBitCast(FromVal, ToType);
777207618Srdivacky
778207618Srdivacky    // Otherwise it must be an element access.
779207618Srdivacky    unsigned Elt = 0;
780207618Srdivacky    if (Offset) {
781207618Srdivacky      unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
782207618Srdivacky      Elt = Offset/EltSize;
783207618Srdivacky      assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
784207618Srdivacky    }
785207618Srdivacky    // Return the element extracted out of it.
786245431Sdim    Value *Idx;
787245431Sdim    if (NonConstantIdx) {
788245431Sdim      if (Elt)
789245431Sdim        Idx = Builder.CreateAdd(NonConstantIdx,
790245431Sdim                                Builder.getInt32(Elt),
791245431Sdim                                "dyn.offset");
792245431Sdim      else
793245431Sdim        Idx = NonConstantIdx;
794245431Sdim    } else
795245431Sdim      Idx = Builder.getInt32(Elt);
796245431Sdim    Value *V = Builder.CreateExtractElement(FromVal, Idx);
797207618Srdivacky    if (V->getType() != ToType)
798226890Sdim      V = Builder.CreateBitCast(V, ToType);
799207618Srdivacky    return V;
800207618Srdivacky  }
801218893Sdim
802207618Srdivacky  // If ToType is a first class aggregate, extract out each of the pieces and
803207618Srdivacky  // use insertvalue's to form the FCA.
804226890Sdim  if (StructType *ST = dyn_cast<StructType>(ToType)) {
805245431Sdim    assert(!NonConstantIdx &&
806245431Sdim           "Dynamic indexing into struct types not supported");
807207618Srdivacky    const StructLayout &Layout = *TD.getStructLayout(ST);
808207618Srdivacky    Value *Res = UndefValue::get(ST);
809207618Srdivacky    for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
810207618Srdivacky      Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
811207618Srdivacky                                        Offset+Layout.getElementOffsetInBits(i),
812245431Sdim                                              0, Builder);
813226890Sdim      Res = Builder.CreateInsertValue(Res, Elt, i);
814207618Srdivacky    }
815207618Srdivacky    return Res;
816207618Srdivacky  }
817218893Sdim
818226890Sdim  if (ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
819245431Sdim    assert(!NonConstantIdx &&
820245431Sdim           "Dynamic indexing into array types not supported");
821207618Srdivacky    uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
822207618Srdivacky    Value *Res = UndefValue::get(AT);
823207618Srdivacky    for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
824207618Srdivacky      Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
825245431Sdim                                              Offset+i*EltSize, 0, Builder);
826226890Sdim      Res = Builder.CreateInsertValue(Res, Elt, i);
827207618Srdivacky    }
828207618Srdivacky    return Res;
829207618Srdivacky  }
830207618Srdivacky
831207618Srdivacky  // Otherwise, this must be a union that was converted to an integer value.
832226890Sdim  IntegerType *NTy = cast<IntegerType>(FromVal->getType());
833207618Srdivacky
834207618Srdivacky  // If this is a big-endian system and the load is narrower than the
835207618Srdivacky  // full alloca type, we need to do a shift to get the right bits.
836207618Srdivacky  int ShAmt = 0;
837207618Srdivacky  if (TD.isBigEndian()) {
838207618Srdivacky    // On big-endian machines, the lowest bit is stored at the bit offset
839207618Srdivacky    // from the pointer given by getTypeStoreSizeInBits.  This matters for
840207618Srdivacky    // integers with a bitwidth that is not a multiple of 8.
841207618Srdivacky    ShAmt = TD.getTypeStoreSizeInBits(NTy) -
842207618Srdivacky            TD.getTypeStoreSizeInBits(ToType) - Offset;
843207618Srdivacky  } else {
844207618Srdivacky    ShAmt = Offset;
845207618Srdivacky  }
846207618Srdivacky
847207618Srdivacky  // Note: we support negative bitwidths (with shl) which are not defined.
848207618Srdivacky  // We do this to support (f.e.) loads off the end of a structure where
849207618Srdivacky  // only some bits are used.
850207618Srdivacky  if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
851207618Srdivacky    FromVal = Builder.CreateLShr(FromVal,
852226890Sdim                                 ConstantInt::get(FromVal->getType(), ShAmt));
853207618Srdivacky  else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
854218893Sdim    FromVal = Builder.CreateShl(FromVal,
855226890Sdim                                ConstantInt::get(FromVal->getType(), -ShAmt));
856207618Srdivacky
857207618Srdivacky  // Finally, unconditionally truncate the integer to the right width.
858207618Srdivacky  unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
859207618Srdivacky  if (LIBitWidth < NTy->getBitWidth())
860207618Srdivacky    FromVal =
861218893Sdim      Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
862226890Sdim                                                    LIBitWidth));
863207618Srdivacky  else if (LIBitWidth > NTy->getBitWidth())
864207618Srdivacky    FromVal =
865218893Sdim       Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
866226890Sdim                                                    LIBitWidth));
867207618Srdivacky
868207618Srdivacky  // If the result is an integer, this is a trunc or bitcast.
869207618Srdivacky  if (ToType->isIntegerTy()) {
870207618Srdivacky    // Should be done.
871207618Srdivacky  } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
872207618Srdivacky    // Just do a bitcast, we know the sizes match up.
873226890Sdim    FromVal = Builder.CreateBitCast(FromVal, ToType);
874207618Srdivacky  } else {
875207618Srdivacky    // Otherwise must be a pointer.
876226890Sdim    FromVal = Builder.CreateIntToPtr(FromVal, ToType);
877207618Srdivacky  }
878207618Srdivacky  assert(FromVal->getType() == ToType && "Didn't convert right?");
879207618Srdivacky  return FromVal;
880207618Srdivacky}
881207618Srdivacky
882207618Srdivacky/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
883207618Srdivacky/// or vector value "Old" at the offset specified by Offset.
884207618Srdivacky///
885207618Srdivacky/// This happens when we are converting an "integer union" to a
886207618Srdivacky/// single integer scalar, or when we are converting a "vector union" to a
887207618Srdivacky/// vector with insert/extractelement instructions.
888207618Srdivacky///
889207618Srdivacky/// Offset is an offset from the original alloca, in bits that need to be
890207618Srdivacky/// shifted to the right.
891245431Sdim///
892245431Sdim/// NonConstantIdx is an index value if there was a GEP with a non-constant
893245431Sdim/// index value.  If this is 0 then all GEPs used to find this insert address
894245431Sdim/// are constant.
895207618SrdivackyValue *ConvertToScalarInfo::
896207618SrdivackyConvertScalar_InsertValue(Value *SV, Value *Old,
897245431Sdim                          uint64_t Offset, Value* NonConstantIdx,
898245431Sdim                          IRBuilder<> &Builder) {
899207618Srdivacky  // Convert the stored type to the actual type, shift it left to insert
900207618Srdivacky  // then 'or' into place.
901226890Sdim  Type *AllocaType = Old->getType();
902207618Srdivacky  LLVMContext &Context = Old->getContext();
903207618Srdivacky
904226890Sdim  if (VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
905207618Srdivacky    uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
906207618Srdivacky    uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
907218893Sdim
908207618Srdivacky    // Changing the whole vector with memset or with an access of a different
909207618Srdivacky    // vector type?
910226890Sdim    if (ValSize == VecSize)
911226890Sdim        return Builder.CreateBitCast(SV, AllocaType);
912207618Srdivacky
913207618Srdivacky    // Must be an element insertion.
914235633Sdim    Type *EltTy = VTy->getElementType();
915235633Sdim    if (SV->getType() != EltTy)
916235633Sdim      SV = Builder.CreateBitCast(SV, EltTy);
917235633Sdim    uint64_t EltSize = TD.getTypeAllocSizeInBits(EltTy);
918207618Srdivacky    unsigned Elt = Offset/EltSize;
919245431Sdim    Value *Idx;
920245431Sdim    if (NonConstantIdx) {
921245431Sdim      if (Elt)
922245431Sdim        Idx = Builder.CreateAdd(NonConstantIdx,
923245431Sdim                                Builder.getInt32(Elt),
924245431Sdim                                "dyn.offset");
925245431Sdim      else
926245431Sdim        Idx = NonConstantIdx;
927245431Sdim    } else
928245431Sdim      Idx = Builder.getInt32(Elt);
929245431Sdim    return Builder.CreateInsertElement(Old, SV, Idx);
930207618Srdivacky  }
931218893Sdim
932207618Srdivacky  // If SV is a first-class aggregate value, insert each value recursively.
933226890Sdim  if (StructType *ST = dyn_cast<StructType>(SV->getType())) {
934245431Sdim    assert(!NonConstantIdx &&
935245431Sdim           "Dynamic indexing into struct types not supported");
936207618Srdivacky    const StructLayout &Layout = *TD.getStructLayout(ST);
937207618Srdivacky    for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
938226890Sdim      Value *Elt = Builder.CreateExtractValue(SV, i);
939218893Sdim      Old = ConvertScalar_InsertValue(Elt, Old,
940207618Srdivacky                                      Offset+Layout.getElementOffsetInBits(i),
941245431Sdim                                      0, Builder);
942207618Srdivacky    }
943207618Srdivacky    return Old;
944207618Srdivacky  }
945218893Sdim
946226890Sdim  if (ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
947245431Sdim    assert(!NonConstantIdx &&
948245431Sdim           "Dynamic indexing into array types not supported");
949207618Srdivacky    uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
950207618Srdivacky    for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
951226890Sdim      Value *Elt = Builder.CreateExtractValue(SV, i);
952245431Sdim      Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, 0, Builder);
953207618Srdivacky    }
954207618Srdivacky    return Old;
955207618Srdivacky  }
956207618Srdivacky
957207618Srdivacky  // If SV is a float, convert it to the appropriate integer type.
958207618Srdivacky  // If it is a pointer, do the same.
959207618Srdivacky  unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
960207618Srdivacky  unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
961207618Srdivacky  unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
962207618Srdivacky  unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
963207618Srdivacky  if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
964226890Sdim    SV = Builder.CreateBitCast(SV, IntegerType::get(SV->getContext(),SrcWidth));
965207618Srdivacky  else if (SV->getType()->isPointerTy())
966263509Sdim    SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getType()));
967207618Srdivacky
968207618Srdivacky  // Zero extend or truncate the value if needed.
969207618Srdivacky  if (SV->getType() != AllocaType) {
970207618Srdivacky    if (SV->getType()->getPrimitiveSizeInBits() <
971207618Srdivacky             AllocaType->getPrimitiveSizeInBits())
972226890Sdim      SV = Builder.CreateZExt(SV, AllocaType);
973207618Srdivacky    else {
974207618Srdivacky      // Truncation may be needed if storing more than the alloca can hold
975207618Srdivacky      // (undefined behavior).
976226890Sdim      SV = Builder.CreateTrunc(SV, AllocaType);
977207618Srdivacky      SrcWidth = DestWidth;
978207618Srdivacky      SrcStoreWidth = DestStoreWidth;
979207618Srdivacky    }
980207618Srdivacky  }
981207618Srdivacky
982207618Srdivacky  // If this is a big-endian system and the store is narrower than the
983207618Srdivacky  // full alloca type, we need to do a shift to get the right bits.
984207618Srdivacky  int ShAmt = 0;
985207618Srdivacky  if (TD.isBigEndian()) {
986207618Srdivacky    // On big-endian machines, the lowest bit is stored at the bit offset
987207618Srdivacky    // from the pointer given by getTypeStoreSizeInBits.  This matters for
988207618Srdivacky    // integers with a bitwidth that is not a multiple of 8.
989207618Srdivacky    ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
990207618Srdivacky  } else {
991207618Srdivacky    ShAmt = Offset;
992207618Srdivacky  }
993207618Srdivacky
994207618Srdivacky  // Note: we support negative bitwidths (with shr) which are not defined.
995207618Srdivacky  // We do this to support (f.e.) stores off the end of a structure where
996207618Srdivacky  // only some bits in the structure are set.
997207618Srdivacky  APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
998207618Srdivacky  if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
999226890Sdim    SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(), ShAmt));
1000207618Srdivacky    Mask <<= ShAmt;
1001207618Srdivacky  } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1002226890Sdim    SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(), -ShAmt));
1003207618Srdivacky    Mask = Mask.lshr(-ShAmt);
1004207618Srdivacky  }
1005207618Srdivacky
1006207618Srdivacky  // Mask out the bits we are about to insert from the old value, and or
1007207618Srdivacky  // in the new bits.
1008207618Srdivacky  if (SrcWidth != DestWidth) {
1009207618Srdivacky    assert(DestWidth > SrcWidth);
1010207618Srdivacky    Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
1011207618Srdivacky    SV = Builder.CreateOr(Old, SV, "ins");
1012207618Srdivacky  }
1013207618Srdivacky  return SV;
1014207618Srdivacky}
1015207618Srdivacky
1016207618Srdivacky
1017207618Srdivacky//===----------------------------------------------------------------------===//
1018207618Srdivacky// SRoA Driver
1019207618Srdivacky//===----------------------------------------------------------------------===//
1020207618Srdivacky
1021207618Srdivacky
1022193323Sedbool SROA::runOnFunction(Function &F) {
1023245431Sdim  TD = getAnalysisIfAvailable<DataLayout>();
1024198090Srdivacky
1025193323Sed  bool Changed = performPromotion(F);
1026198090Srdivacky
1027245431Sdim  // FIXME: ScalarRepl currently depends on DataLayout more than it
1028198090Srdivacky  // theoretically needs to. It should be refactored in order to support
1029198090Srdivacky  // target-independent IR. Until this is done, just skip the actual
1030198090Srdivacky  // scalar-replacement portion of this pass.
1031198090Srdivacky  if (!TD) return Changed;
1032198090Srdivacky
1033193323Sed  while (1) {
1034193323Sed    bool LocalChange = performScalarRepl(F);
1035193323Sed    if (!LocalChange) break;   // No need to repromote if no scalarrepl
1036193323Sed    Changed = true;
1037193323Sed    LocalChange = performPromotion(F);
1038193323Sed    if (!LocalChange) break;   // No need to re-scalarrepl if no promotion
1039193323Sed  }
1040193323Sed
1041193323Sed  return Changed;
1042193323Sed}
1043193323Sed
1044218893Sdimnamespace {
1045218893Sdimclass AllocaPromoter : public LoadAndStorePromoter {
1046218893Sdim  AllocaInst *AI;
1047224145Sdim  DIBuilder *DIB;
1048224145Sdim  SmallVector<DbgDeclareInst *, 4> DDIs;
1049224145Sdim  SmallVector<DbgValueInst *, 4> DVIs;
1050218893Sdimpublic:
1051223017Sdim  AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1052224145Sdim                 DIBuilder *DB)
1053224145Sdim    : LoadAndStorePromoter(Insts, S), AI(0), DIB(DB) {}
1054245431Sdim
1055218893Sdim  void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
1056218893Sdim    // Remember which alloca we're promoting (for isInstInList).
1057218893Sdim    this->AI = AI;
1058235633Sdim    if (MDNode *DebugNode = MDNode::getIfExists(AI->getContext(), AI)) {
1059224145Sdim      for (Value::use_iterator UI = DebugNode->use_begin(),
1060224145Sdim             E = DebugNode->use_end(); UI != E; ++UI)
1061224145Sdim        if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
1062224145Sdim          DDIs.push_back(DDI);
1063224145Sdim        else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
1064224145Sdim          DVIs.push_back(DVI);
1065235633Sdim    }
1066224145Sdim
1067218893Sdim    LoadAndStorePromoter::run(Insts);
1068218893Sdim    AI->eraseFromParent();
1069263509Sdim    for (SmallVectorImpl<DbgDeclareInst *>::iterator I = DDIs.begin(),
1070224145Sdim           E = DDIs.end(); I != E; ++I) {
1071224145Sdim      DbgDeclareInst *DDI = *I;
1072224145Sdim      DDI->eraseFromParent();
1073224145Sdim    }
1074263509Sdim    for (SmallVectorImpl<DbgValueInst *>::iterator I = DVIs.begin(),
1075224145Sdim           E = DVIs.end(); I != E; ++I) {
1076224145Sdim      DbgValueInst *DVI = *I;
1077224145Sdim      DVI->eraseFromParent();
1078224145Sdim    }
1079218893Sdim  }
1080245431Sdim
1081218893Sdim  virtual bool isInstInList(Instruction *I,
1082218893Sdim                            const SmallVectorImpl<Instruction*> &Insts) const {
1083218893Sdim    if (LoadInst *LI = dyn_cast<LoadInst>(I))
1084218893Sdim      return LI->getOperand(0) == AI;
1085218893Sdim    return cast<StoreInst>(I)->getPointerOperand() == AI;
1086218893Sdim  }
1087224145Sdim
1088224145Sdim  virtual void updateDebugInfo(Instruction *Inst) const {
1089263509Sdim    for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
1090224145Sdim           E = DDIs.end(); I != E; ++I) {
1091224145Sdim      DbgDeclareInst *DDI = *I;
1092224145Sdim      if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1093224145Sdim        ConvertDebugDeclareToDebugValue(DDI, SI, *DIB);
1094224145Sdim      else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1095224145Sdim        ConvertDebugDeclareToDebugValue(DDI, LI, *DIB);
1096224145Sdim    }
1097263509Sdim    for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
1098224145Sdim           E = DVIs.end(); I != E; ++I) {
1099224145Sdim      DbgValueInst *DVI = *I;
1100235633Sdim      Value *Arg = NULL;
1101224145Sdim      if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1102224145Sdim        // If an argument is zero extended then use argument directly. The ZExt
1103224145Sdim        // may be zapped by an optimization pass in future.
1104224145Sdim        if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1105235633Sdim          Arg = dyn_cast<Argument>(ZExt->getOperand(0));
1106224145Sdim        if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1107235633Sdim          Arg = dyn_cast<Argument>(SExt->getOperand(0));
1108235633Sdim        if (!Arg)
1109235633Sdim          Arg = SI->getOperand(0);
1110224145Sdim      } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1111235633Sdim        Arg = LI->getOperand(0);
1112235633Sdim      } else {
1113235633Sdim        continue;
1114224145Sdim      }
1115235633Sdim      Instruction *DbgVal =
1116235633Sdim        DIB->insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1117235633Sdim                                     Inst);
1118235633Sdim      DbgVal->setDebugLoc(DVI->getDebugLoc());
1119224145Sdim    }
1120224145Sdim  }
1121218893Sdim};
1122218893Sdim} // end anon namespace
1123193323Sed
1124218893Sdim/// isSafeSelectToSpeculate - Select instructions that use an alloca and are
1125218893Sdim/// subsequently loaded can be rewritten to load both input pointers and then
1126218893Sdim/// select between the result, allowing the load of the alloca to be promoted.
1127218893Sdim/// From this:
1128218893Sdim///   %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1129218893Sdim///   %V = load i32* %P2
1130218893Sdim/// to:
1131218893Sdim///   %V1 = load i32* %Alloca      -> will be mem2reg'd
1132218893Sdim///   %V2 = load i32* %Other
1133218893Sdim///   %V = select i1 %cond, i32 %V1, i32 %V2
1134218893Sdim///
1135218893Sdim/// We can do this to a select if its only uses are loads and if the operand to
1136218893Sdim/// the select can be loaded unconditionally.
1137245431Sdimstatic bool isSafeSelectToSpeculate(SelectInst *SI, const DataLayout *TD) {
1138218893Sdim  bool TDerefable = SI->getTrueValue()->isDereferenceablePointer();
1139218893Sdim  bool FDerefable = SI->getFalseValue()->isDereferenceablePointer();
1140245431Sdim
1141218893Sdim  for (Value::use_iterator UI = SI->use_begin(), UE = SI->use_end();
1142218893Sdim       UI != UE; ++UI) {
1143218893Sdim    LoadInst *LI = dyn_cast<LoadInst>(*UI);
1144226890Sdim    if (LI == 0 || !LI->isSimple()) return false;
1145245431Sdim
1146218893Sdim    // Both operands to the select need to be dereferencable, either absolutely
1147218893Sdim    // (e.g. allocas) or at this point because we can see other accesses to it.
1148218893Sdim    if (!TDerefable && !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
1149218893Sdim                                                    LI->getAlignment(), TD))
1150218893Sdim      return false;
1151218893Sdim    if (!FDerefable && !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
1152218893Sdim                                                    LI->getAlignment(), TD))
1153218893Sdim      return false;
1154218893Sdim  }
1155245431Sdim
1156218893Sdim  return true;
1157218893Sdim}
1158218893Sdim
1159218893Sdim/// isSafePHIToSpeculate - PHI instructions that use an alloca and are
1160218893Sdim/// subsequently loaded can be rewritten to load both input pointers in the pred
1161218893Sdim/// blocks and then PHI the results, allowing the load of the alloca to be
1162218893Sdim/// promoted.
1163218893Sdim/// From this:
1164218893Sdim///   %P2 = phi [i32* %Alloca, i32* %Other]
1165218893Sdim///   %V = load i32* %P2
1166218893Sdim/// to:
1167218893Sdim///   %V1 = load i32* %Alloca      -> will be mem2reg'd
1168218893Sdim///   ...
1169218893Sdim///   %V2 = load i32* %Other
1170218893Sdim///   ...
1171218893Sdim///   %V = phi [i32 %V1, i32 %V2]
1172218893Sdim///
1173218893Sdim/// We can do this to a select if its only uses are loads and if the operand to
1174218893Sdim/// the select can be loaded unconditionally.
1175245431Sdimstatic bool isSafePHIToSpeculate(PHINode *PN, const DataLayout *TD) {
1176218893Sdim  // For now, we can only do this promotion if the load is in the same block as
1177218893Sdim  // the PHI, and if there are no stores between the phi and load.
1178218893Sdim  // TODO: Allow recursive phi users.
1179218893Sdim  // TODO: Allow stores.
1180218893Sdim  BasicBlock *BB = PN->getParent();
1181218893Sdim  unsigned MaxAlign = 0;
1182218893Sdim  for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
1183218893Sdim       UI != UE; ++UI) {
1184218893Sdim    LoadInst *LI = dyn_cast<LoadInst>(*UI);
1185226890Sdim    if (LI == 0 || !LI->isSimple()) return false;
1186245431Sdim
1187218893Sdim    // For now we only allow loads in the same block as the PHI.  This is a
1188218893Sdim    // common case that happens when instcombine merges two loads through a PHI.
1189218893Sdim    if (LI->getParent() != BB) return false;
1190245431Sdim
1191218893Sdim    // Ensure that there are no instructions between the PHI and the load that
1192218893Sdim    // could store.
1193218893Sdim    for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
1194218893Sdim      if (BBI->mayWriteToMemory())
1195218893Sdim        return false;
1196245431Sdim
1197218893Sdim    MaxAlign = std::max(MaxAlign, LI->getAlignment());
1198218893Sdim  }
1199245431Sdim
1200218893Sdim  // Okay, we know that we have one or more loads in the same block as the PHI.
1201218893Sdim  // We can transform this if it is safe to push the loads into the predecessor
1202218893Sdim  // blocks.  The only thing to watch out for is that we can't put a possibly
1203218893Sdim  // trapping load in the predecessor if it is a critical edge.
1204218893Sdim  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1205218893Sdim    BasicBlock *Pred = PN->getIncomingBlock(i);
1206226890Sdim    Value *InVal = PN->getIncomingValue(i);
1207218893Sdim
1208226890Sdim    // If the terminator of the predecessor has side-effects (an invoke),
1209226890Sdim    // there is no safe place to put a load in the predecessor.
1210226890Sdim    if (Pred->getTerminator()->mayHaveSideEffects())
1211226890Sdim      return false;
1212226890Sdim
1213226890Sdim    // If the value is produced by the terminator of the predecessor
1214226890Sdim    // (an invoke), there is no valid place to put a load in the predecessor.
1215226890Sdim    if (Pred->getTerminator() == InVal)
1216226890Sdim      return false;
1217226890Sdim
1218218893Sdim    // If the predecessor has a single successor, then the edge isn't critical.
1219218893Sdim    if (Pred->getTerminator()->getNumSuccessors() == 1)
1220218893Sdim      continue;
1221218893Sdim
1222218893Sdim    // If this pointer is always safe to load, or if we can prove that there is
1223218893Sdim    // already a load in the block, then we can move the load to the pred block.
1224218893Sdim    if (InVal->isDereferenceablePointer() ||
1225218893Sdim        isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign, TD))
1226218893Sdim      continue;
1227245431Sdim
1228218893Sdim    return false;
1229218893Sdim  }
1230245431Sdim
1231218893Sdim  return true;
1232218893Sdim}
1233218893Sdim
1234218893Sdim
1235218893Sdim/// tryToMakeAllocaBePromotable - This returns true if the alloca only has
1236218893Sdim/// direct (non-volatile) loads and stores to it.  If the alloca is close but
1237218893Sdim/// not quite there, this will transform the code to allow promotion.  As such,
1238218893Sdim/// it is a non-pure predicate.
1239245431Sdimstatic bool tryToMakeAllocaBePromotable(AllocaInst *AI, const DataLayout *TD) {
1240218893Sdim  SetVector<Instruction*, SmallVector<Instruction*, 4>,
1241218893Sdim            SmallPtrSet<Instruction*, 4> > InstsToRewrite;
1242245431Sdim
1243218893Sdim  for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
1244218893Sdim       UI != UE; ++UI) {
1245218893Sdim    User *U = *UI;
1246218893Sdim    if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1247226890Sdim      if (!LI->isSimple())
1248218893Sdim        return false;
1249218893Sdim      continue;
1250218893Sdim    }
1251245431Sdim
1252218893Sdim    if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1253226890Sdim      if (SI->getOperand(0) == AI || !SI->isSimple())
1254218893Sdim        return false;   // Don't allow a store OF the AI, only INTO the AI.
1255218893Sdim      continue;
1256218893Sdim    }
1257218893Sdim
1258218893Sdim    if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
1259218893Sdim      // If the condition being selected on is a constant, fold the select, yes
1260218893Sdim      // this does (rarely) happen early on.
1261218893Sdim      if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
1262218893Sdim        Value *Result = SI->getOperand(1+CI->isZero());
1263218893Sdim        SI->replaceAllUsesWith(Result);
1264218893Sdim        SI->eraseFromParent();
1265245431Sdim
1266218893Sdim        // This is very rare and we just scrambled the use list of AI, start
1267218893Sdim        // over completely.
1268218893Sdim        return tryToMakeAllocaBePromotable(AI, TD);
1269218893Sdim      }
1270218893Sdim
1271218893Sdim      // If it is safe to turn "load (select c, AI, ptr)" into a select of two
1272218893Sdim      // loads, then we can transform this by rewriting the select.
1273218893Sdim      if (!isSafeSelectToSpeculate(SI, TD))
1274218893Sdim        return false;
1275245431Sdim
1276218893Sdim      InstsToRewrite.insert(SI);
1277218893Sdim      continue;
1278218893Sdim    }
1279245431Sdim
1280218893Sdim    if (PHINode *PN = dyn_cast<PHINode>(U)) {
1281218893Sdim      if (PN->use_empty()) {  // Dead PHIs can be stripped.
1282218893Sdim        InstsToRewrite.insert(PN);
1283218893Sdim        continue;
1284218893Sdim      }
1285245431Sdim
1286218893Sdim      // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
1287218893Sdim      // in the pred blocks, then we can transform this by rewriting the PHI.
1288218893Sdim      if (!isSafePHIToSpeculate(PN, TD))
1289218893Sdim        return false;
1290245431Sdim
1291218893Sdim      InstsToRewrite.insert(PN);
1292218893Sdim      continue;
1293218893Sdim    }
1294245431Sdim
1295226890Sdim    if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
1296226890Sdim      if (onlyUsedByLifetimeMarkers(BCI)) {
1297226890Sdim        InstsToRewrite.insert(BCI);
1298226890Sdim        continue;
1299226890Sdim      }
1300226890Sdim    }
1301245431Sdim
1302218893Sdim    return false;
1303218893Sdim  }
1304218893Sdim
1305218893Sdim  // If there are no instructions to rewrite, then all uses are load/stores and
1306218893Sdim  // we're done!
1307218893Sdim  if (InstsToRewrite.empty())
1308218893Sdim    return true;
1309245431Sdim
1310218893Sdim  // If we have instructions that need to be rewritten for this to be promotable
1311218893Sdim  // take care of it now.
1312218893Sdim  for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
1313226890Sdim    if (BitCastInst *BCI = dyn_cast<BitCastInst>(InstsToRewrite[i])) {
1314226890Sdim      // This could only be a bitcast used by nothing but lifetime intrinsics.
1315226890Sdim      for (BitCastInst::use_iterator I = BCI->use_begin(), E = BCI->use_end();
1316226890Sdim           I != E;) {
1317226890Sdim        Use &U = I.getUse();
1318226890Sdim        ++I;
1319226890Sdim        cast<Instruction>(U.getUser())->eraseFromParent();
1320226890Sdim      }
1321226890Sdim      BCI->eraseFromParent();
1322226890Sdim      continue;
1323226890Sdim    }
1324226890Sdim
1325218893Sdim    if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
1326218893Sdim      // Selects in InstsToRewrite only have load uses.  Rewrite each as two
1327218893Sdim      // loads with a new select.
1328218893Sdim      while (!SI->use_empty()) {
1329218893Sdim        LoadInst *LI = cast<LoadInst>(SI->use_back());
1330245431Sdim
1331218893Sdim        IRBuilder<> Builder(LI);
1332245431Sdim        LoadInst *TrueLoad =
1333218893Sdim          Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t");
1334245431Sdim        LoadInst *FalseLoad =
1335224145Sdim          Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".f");
1336245431Sdim
1337218893Sdim        // Transfer alignment and TBAA info if present.
1338218893Sdim        TrueLoad->setAlignment(LI->getAlignment());
1339218893Sdim        FalseLoad->setAlignment(LI->getAlignment());
1340218893Sdim        if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1341218893Sdim          TrueLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1342218893Sdim          FalseLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1343218893Sdim        }
1344245431Sdim
1345218893Sdim        Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
1346218893Sdim        V->takeName(LI);
1347218893Sdim        LI->replaceAllUsesWith(V);
1348218893Sdim        LI->eraseFromParent();
1349218893Sdim      }
1350245431Sdim
1351218893Sdim      // Now that all the loads are gone, the select is gone too.
1352218893Sdim      SI->eraseFromParent();
1353218893Sdim      continue;
1354218893Sdim    }
1355245431Sdim
1356218893Sdim    // Otherwise, we have a PHI node which allows us to push the loads into the
1357218893Sdim    // predecessors.
1358218893Sdim    PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
1359218893Sdim    if (PN->use_empty()) {
1360218893Sdim      PN->eraseFromParent();
1361218893Sdim      continue;
1362218893Sdim    }
1363245431Sdim
1364226890Sdim    Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
1365221345Sdim    PHINode *NewPN = PHINode::Create(LoadTy, PN->getNumIncomingValues(),
1366221345Sdim                                     PN->getName()+".ld", PN);
1367218893Sdim
1368218893Sdim    // Get the TBAA tag and alignment to use from one of the loads.  It doesn't
1369218893Sdim    // matter which one we get and if any differ, it doesn't matter.
1370218893Sdim    LoadInst *SomeLoad = cast<LoadInst>(PN->use_back());
1371218893Sdim    MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1372218893Sdim    unsigned Align = SomeLoad->getAlignment();
1373245431Sdim
1374218893Sdim    // Rewrite all loads of the PN to use the new PHI.
1375218893Sdim    while (!PN->use_empty()) {
1376218893Sdim      LoadInst *LI = cast<LoadInst>(PN->use_back());
1377218893Sdim      LI->replaceAllUsesWith(NewPN);
1378218893Sdim      LI->eraseFromParent();
1379218893Sdim    }
1380245431Sdim
1381218893Sdim    // Inject loads into all of the pred blocks.  Keep track of which blocks we
1382218893Sdim    // insert them into in case we have multiple edges from the same block.
1383218893Sdim    DenseMap<BasicBlock*, LoadInst*> InsertedLoads;
1384245431Sdim
1385218893Sdim    for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1386218893Sdim      BasicBlock *Pred = PN->getIncomingBlock(i);
1387218893Sdim      LoadInst *&Load = InsertedLoads[Pred];
1388218893Sdim      if (Load == 0) {
1389218893Sdim        Load = new LoadInst(PN->getIncomingValue(i),
1390218893Sdim                            PN->getName() + "." + Pred->getName(),
1391218893Sdim                            Pred->getTerminator());
1392218893Sdim        Load->setAlignment(Align);
1393218893Sdim        if (TBAATag) Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1394218893Sdim      }
1395245431Sdim
1396218893Sdim      NewPN->addIncoming(Load, Pred);
1397218893Sdim    }
1398245431Sdim
1399218893Sdim    PN->eraseFromParent();
1400218893Sdim  }
1401245431Sdim
1402218893Sdim  ++NumAdjusted;
1403218893Sdim  return true;
1404218893Sdim}
1405218893Sdim
1406193323Sedbool SROA::performPromotion(Function &F) {
1407193323Sed  std::vector<AllocaInst*> Allocas;
1408218893Sdim  DominatorTree *DT = 0;
1409218893Sdim  if (HasDomTree)
1410218893Sdim    DT = &getAnalysis<DominatorTree>();
1411193323Sed
1412193323Sed  BasicBlock &BB = F.getEntryBlock();  // Get the entry node for the function
1413224145Sdim  DIBuilder DIB(*F.getParent());
1414193323Sed  bool Changed = false;
1415218893Sdim  SmallVector<Instruction*, 64> Insts;
1416193323Sed  while (1) {
1417193323Sed    Allocas.clear();
1418193323Sed
1419193323Sed    // Find allocas that are safe to promote, by looking at all instructions in
1420193323Sed    // the entry node
1421193323Sed    for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
1422193323Sed      if (AllocaInst *AI = dyn_cast<AllocaInst>(I))       // Is it an alloca?
1423218893Sdim        if (tryToMakeAllocaBePromotable(AI, TD))
1424193323Sed          Allocas.push_back(AI);
1425193323Sed
1426193323Sed    if (Allocas.empty()) break;
1427193323Sed
1428218893Sdim    if (HasDomTree)
1429218893Sdim      PromoteMemToReg(Allocas, *DT);
1430218893Sdim    else {
1431218893Sdim      SSAUpdater SSA;
1432218893Sdim      for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
1433218893Sdim        AllocaInst *AI = Allocas[i];
1434245431Sdim
1435218893Sdim        // Build list of instructions to promote.
1436218893Sdim        for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1437218893Sdim             UI != E; ++UI)
1438218893Sdim          Insts.push_back(cast<Instruction>(*UI));
1439224145Sdim        AllocaPromoter(Insts, SSA, &DIB).run(AI, Insts);
1440218893Sdim        Insts.clear();
1441218893Sdim      }
1442218893Sdim    }
1443193323Sed    NumPromoted += Allocas.size();
1444193323Sed    Changed = true;
1445193323Sed  }
1446193323Sed
1447193323Sed  return Changed;
1448193323Sed}
1449193323Sed
1450207618Srdivacky
1451203954Srdivacky/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
1452203954Srdivacky/// SROA.  It must be a struct or array type with a small number of elements.
1453245431Sdimbool SROA::ShouldAttemptScalarRepl(AllocaInst *AI) {
1454226890Sdim  Type *T = AI->getAllocatedType();
1455245431Sdim  // Do not promote any struct that has too many members.
1456226890Sdim  if (StructType *ST = dyn_cast<StructType>(T))
1457245431Sdim    return ST->getNumElements() <= StructMemberThreshold;
1458245431Sdim  // Do not promote any array that has too many elements.
1459226890Sdim  if (ArrayType *AT = dyn_cast<ArrayType>(T))
1460245431Sdim    return AT->getNumElements() <= ArrayElementThreshold;
1461203954Srdivacky  return false;
1462193323Sed}
1463193323Sed
1464193323Sed// performScalarRepl - This algorithm is a simple worklist driven algorithm,
1465252723Sdim// which runs on all of the alloca instructions in the entry block, removing
1466252723Sdim// them if they are only used by getelementptr instructions.
1467193323Sed//
1468193323Sedbool SROA::performScalarRepl(Function &F) {
1469198892Srdivacky  std::vector<AllocaInst*> WorkList;
1470193323Sed
1471207618Srdivacky  // Scan the entry basic block, adding allocas to the worklist.
1472193323Sed  BasicBlock &BB = F.getEntryBlock();
1473193323Sed  for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
1474198892Srdivacky    if (AllocaInst *A = dyn_cast<AllocaInst>(I))
1475193323Sed      WorkList.push_back(A);
1476193323Sed
1477193323Sed  // Process the worklist
1478193323Sed  bool Changed = false;
1479193323Sed  while (!WorkList.empty()) {
1480198892Srdivacky    AllocaInst *AI = WorkList.back();
1481193323Sed    WorkList.pop_back();
1482218893Sdim
1483193323Sed    // Handle dead allocas trivially.  These can be formed by SROA'ing arrays
1484193323Sed    // with unused elements.
1485193323Sed    if (AI->use_empty()) {
1486193323Sed      AI->eraseFromParent();
1487207618Srdivacky      Changed = true;
1488193323Sed      continue;
1489193323Sed    }
1490193323Sed
1491193323Sed    // If this alloca is impossible for us to promote, reject it early.
1492193323Sed    if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
1493193323Sed      continue;
1494218893Sdim
1495193323Sed    // Check to see if we can perform the core SROA transformation.  We cannot
1496193323Sed    // transform the allocation instruction if it is an array allocation
1497193323Sed    // (allocations OF arrays are ok though), and an allocation of a scalar
1498193323Sed    // value cannot be decomposed at all.
1499193323Sed    uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
1500193323Sed
1501198090Srdivacky    // Do not promote [0 x %struct].
1502198090Srdivacky    if (AllocaSize == 0) continue;
1503218893Sdim
1504207618Srdivacky    // Do not promote any struct whose size is too big.
1505207618Srdivacky    if (AllocaSize > SRThreshold) continue;
1506218893Sdim
1507203954Srdivacky    // If the alloca looks like a good candidate for scalar replacement, and if
1508203954Srdivacky    // all its users can be transformed, then split up the aggregate into its
1509203954Srdivacky    // separate elements.
1510203954Srdivacky    if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
1511203954Srdivacky      DoScalarReplacement(AI, WorkList);
1512203954Srdivacky      Changed = true;
1513203954Srdivacky      continue;
1514203954Srdivacky    }
1515203954Srdivacky
1516193323Sed    // If we can turn this aggregate value (potentially with casts) into a
1517193323Sed    // simple scalar value that can be mem2reg'd into a register value.
1518193323Sed    // IsNotTrivial tracks whether this is something that mem2reg could have
1519193323Sed    // promoted itself.  If so, we don't want to transform it needlessly.  Note
1520193323Sed    // that we can't just check based on the type: the alloca may be of an i32
1521193323Sed    // but that has pointer arithmetic to set byte 3 of it or something.
1522245431Sdim    if (AllocaInst *NewAI = ConvertToScalarInfo(
1523245431Sdim              (unsigned)AllocaSize, *TD, ScalarLoadThreshold).TryConvert(AI)) {
1524193323Sed      NewAI->takeName(AI);
1525193323Sed      AI->eraseFromParent();
1526193323Sed      ++NumConverted;
1527193323Sed      Changed = true;
1528193323Sed      continue;
1529218893Sdim    }
1530218893Sdim
1531193323Sed    // Otherwise, couldn't process this alloca.
1532193323Sed  }
1533193323Sed
1534193323Sed  return Changed;
1535193323Sed}
1536193323Sed
1537193323Sed/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1538193323Sed/// predicate, do SROA now.
1539218893Sdimvoid SROA::DoScalarReplacement(AllocaInst *AI,
1540198892Srdivacky                               std::vector<AllocaInst*> &WorkList) {
1541202375Srdivacky  DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
1542193323Sed  SmallVector<AllocaInst*, 32> ElementAllocas;
1543226890Sdim  if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1544193323Sed    ElementAllocas.reserve(ST->getNumContainedTypes());
1545193323Sed    for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
1546218893Sdim      AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
1547193323Sed                                      AI->getAlignment(),
1548198090Srdivacky                                      AI->getName() + "." + Twine(i), AI);
1549193323Sed      ElementAllocas.push_back(NA);
1550193323Sed      WorkList.push_back(NA);  // Add to worklist for recursive processing
1551193323Sed    }
1552193323Sed  } else {
1553226890Sdim    ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
1554193323Sed    ElementAllocas.reserve(AT->getNumElements());
1555226890Sdim    Type *ElTy = AT->getElementType();
1556193323Sed    for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1557193323Sed      AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
1558198090Srdivacky                                      AI->getName() + "." + Twine(i), AI);
1559193323Sed      ElementAllocas.push_back(NA);
1560193323Sed      WorkList.push_back(NA);  // Add to worklist for recursive processing
1561193323Sed    }
1562193323Sed  }
1563193323Sed
1564201360Srdivacky  // Now that we have created the new alloca instructions, rewrite all the
1565201360Srdivacky  // uses of the old alloca.
1566201360Srdivacky  RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
1567193323Sed
1568201360Srdivacky  // Now erase any instructions that were made dead while rewriting the alloca.
1569201360Srdivacky  DeleteDeadInstructions();
1570201360Srdivacky  AI->eraseFromParent();
1571193323Sed
1572210299Sed  ++NumReplaced;
1573201360Srdivacky}
1574193323Sed
1575201360Srdivacky/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1576201360Srdivacky/// recursively including all their operands that become trivially dead.
1577201360Srdivackyvoid SROA::DeleteDeadInstructions() {
1578201360Srdivacky  while (!DeadInsts.empty()) {
1579201360Srdivacky    Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
1580193323Sed
1581201360Srdivacky    for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1582201360Srdivacky      if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1583201360Srdivacky        // Zero out the operand and see if it becomes trivially dead.
1584201360Srdivacky        // (But, don't add allocas to the dead instruction list -- they are
1585201360Srdivacky        // already on the worklist and will be deleted separately.)
1586201360Srdivacky        *OI = 0;
1587201360Srdivacky        if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1588201360Srdivacky          DeadInsts.push_back(U);
1589201360Srdivacky      }
1590201360Srdivacky
1591201360Srdivacky    I->eraseFromParent();
1592193323Sed  }
1593193323Sed}
1594218893Sdim
1595201360Srdivacky/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1596201360Srdivacky/// performing scalar replacement of alloca AI.  The results are flagged in
1597201360Srdivacky/// the Info parameter.  Offset indicates the position within AI that is
1598201360Srdivacky/// referenced by this instruction.
1599218893Sdimvoid SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
1600201360Srdivacky                               AllocaInfo &Info) {
1601201360Srdivacky  for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1602201360Srdivacky    Instruction *User = cast<Instruction>(*UI);
1603193323Sed
1604201360Srdivacky    if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1605218893Sdim      isSafeForScalarRepl(BC, Offset, Info);
1606201360Srdivacky    } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1607201360Srdivacky      uint64_t GEPOffset = Offset;
1608218893Sdim      isSafeGEP(GEPI, GEPOffset, Info);
1609201360Srdivacky      if (!Info.isUnsafe)
1610218893Sdim        isSafeForScalarRepl(GEPI, GEPOffset, Info);
1611210299Sed    } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1612201360Srdivacky      ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1613218893Sdim      if (Length == 0)
1614218893Sdim        return MarkUnsafe(Info, User);
1615235633Sdim      if (Length->isNegative())
1616235633Sdim        return MarkUnsafe(Info, User);
1617235633Sdim
1618218893Sdim      isSafeMemAccess(Offset, Length->getZExtValue(), 0,
1619218893Sdim                      UI.getOperandNo() == 0, Info, MI,
1620218893Sdim                      true /*AllowWholeAccess*/);
1621201360Srdivacky    } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1622226890Sdim      if (!LI->isSimple())
1623218893Sdim        return MarkUnsafe(Info, User);
1624226890Sdim      Type *LIType = LI->getType();
1625218893Sdim      isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
1626218893Sdim                      LIType, false, Info, LI, true /*AllowWholeAccess*/);
1627218893Sdim      Info.hasALoadOrStore = true;
1628245431Sdim
1629201360Srdivacky    } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1630193323Sed      // Store is ok if storing INTO the pointer, not storing the pointer
1631226890Sdim      if (!SI->isSimple() || SI->getOperand(0) == I)
1632218893Sdim        return MarkUnsafe(Info, User);
1633245431Sdim
1634226890Sdim      Type *SIType = SI->getOperand(0)->getType();
1635218893Sdim      isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
1636218893Sdim                      SIType, true, Info, SI, true /*AllowWholeAccess*/);
1637218893Sdim      Info.hasALoadOrStore = true;
1638226890Sdim    } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
1639226890Sdim      if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1640226890Sdim          II->getIntrinsicID() != Intrinsic::lifetime_end)
1641226890Sdim        return MarkUnsafe(Info, User);
1642218893Sdim    } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1643218893Sdim      isSafePHISelectUseForScalarRepl(User, Offset, Info);
1644201360Srdivacky    } else {
1645218893Sdim      return MarkUnsafe(Info, User);
1646193323Sed    }
1647201360Srdivacky    if (Info.isUnsafe) return;
1648193323Sed  }
1649193323Sed}
1650193323Sed
1651245431Sdim
1652218893Sdim/// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
1653218893Sdim/// derived from the alloca, we can often still split the alloca into elements.
1654218893Sdim/// This is useful if we have a large alloca where one element is phi'd
1655218893Sdim/// together somewhere: we can SRoA and promote all the other elements even if
1656218893Sdim/// we end up not being able to promote this one.
1657218893Sdim///
1658218893Sdim/// All we require is that the uses of the PHI do not index into other parts of
1659218893Sdim/// the alloca.  The most important use case for this is single load and stores
1660218893Sdim/// that are PHI'd together, which can happen due to code sinking.
1661218893Sdimvoid SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
1662218893Sdim                                           AllocaInfo &Info) {
1663218893Sdim  // If we've already checked this PHI, don't do it again.
1664218893Sdim  if (PHINode *PN = dyn_cast<PHINode>(I))
1665218893Sdim    if (!Info.CheckedPHIs.insert(PN))
1666218893Sdim      return;
1667245431Sdim
1668218893Sdim  for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1669218893Sdim    Instruction *User = cast<Instruction>(*UI);
1670245431Sdim
1671218893Sdim    if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1672218893Sdim      isSafePHISelectUseForScalarRepl(BC, Offset, Info);
1673218893Sdim    } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1674218893Sdim      // Only allow "bitcast" GEPs for simplicity.  We could generalize this,
1675218893Sdim      // but would have to prove that we're staying inside of an element being
1676218893Sdim      // promoted.
1677218893Sdim      if (!GEPI->hasAllZeroIndices())
1678218893Sdim        return MarkUnsafe(Info, User);
1679218893Sdim      isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
1680218893Sdim    } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1681226890Sdim      if (!LI->isSimple())
1682218893Sdim        return MarkUnsafe(Info, User);
1683226890Sdim      Type *LIType = LI->getType();
1684218893Sdim      isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
1685218893Sdim                      LIType, false, Info, LI, false /*AllowWholeAccess*/);
1686218893Sdim      Info.hasALoadOrStore = true;
1687245431Sdim
1688218893Sdim    } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1689218893Sdim      // Store is ok if storing INTO the pointer, not storing the pointer
1690226890Sdim      if (!SI->isSimple() || SI->getOperand(0) == I)
1691218893Sdim        return MarkUnsafe(Info, User);
1692245431Sdim
1693226890Sdim      Type *SIType = SI->getOperand(0)->getType();
1694218893Sdim      isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
1695218893Sdim                      SIType, true, Info, SI, false /*AllowWholeAccess*/);
1696218893Sdim      Info.hasALoadOrStore = true;
1697218893Sdim    } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1698218893Sdim      isSafePHISelectUseForScalarRepl(User, Offset, Info);
1699218893Sdim    } else {
1700218893Sdim      return MarkUnsafe(Info, User);
1701218893Sdim    }
1702218893Sdim    if (Info.isUnsafe) return;
1703218893Sdim  }
1704218893Sdim}
1705218893Sdim
1706201360Srdivacky/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1707201360Srdivacky/// replacement.  It is safe when all the indices are constant, in-bounds
1708201360Srdivacky/// references, and when the resulting offset corresponds to an element within
1709201360Srdivacky/// the alloca type.  The results are flagged in the Info parameter.  Upon
1710201360Srdivacky/// return, Offset is adjusted as specified by the GEP indices.
1711218893Sdimvoid SROA::isSafeGEP(GetElementPtrInst *GEPI,
1712201360Srdivacky                     uint64_t &Offset, AllocaInfo &Info) {
1713201360Srdivacky  gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1714201360Srdivacky  if (GEPIt == E)
1715201360Srdivacky    return;
1716245431Sdim  bool NonConstant = false;
1717245431Sdim  unsigned NonConstantIdxSize = 0;
1718193323Sed
1719201360Srdivacky  // Walk through the GEP type indices, checking the types that this indexes
1720201360Srdivacky  // into.
1721201360Srdivacky  for (; GEPIt != E; ++GEPIt) {
1722201360Srdivacky    // Ignore struct elements, no extra checking needed for these.
1723204642Srdivacky    if ((*GEPIt)->isStructTy())
1724201360Srdivacky      continue;
1725193323Sed
1726201360Srdivacky    ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1727252723Sdim    if (!IdxVal)
1728252723Sdim      return MarkUnsafe(Info, GEPI);
1729193323Sed  }
1730193323Sed
1731201360Srdivacky  // Compute the offset due to this GEP and check if the alloca has a
1732201360Srdivacky  // component element at that offset.
1733201360Srdivacky  SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1734245431Sdim  // If this GEP is non constant then the last operand must have been a
1735245431Sdim  // dynamic index into a vector.  Pop this now as it has no impact on the
1736245431Sdim  // constant part of the offset.
1737245431Sdim  if (NonConstant)
1738245431Sdim    Indices.pop_back();
1739226890Sdim  Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
1740245431Sdim  if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset,
1741245431Sdim                        NonConstantIdxSize))
1742218893Sdim    MarkUnsafe(Info, GEPI);
1743201360Srdivacky}
1744193323Sed
1745218893Sdim/// isHomogeneousAggregate - Check if type T is a struct or array containing
1746218893Sdim/// elements of the same type (which is always true for arrays).  If so,
1747218893Sdim/// return true with NumElts and EltTy set to the number of elements and the
1748218893Sdim/// element type, respectively.
1749226890Sdimstatic bool isHomogeneousAggregate(Type *T, unsigned &NumElts,
1750226890Sdim                                   Type *&EltTy) {
1751226890Sdim  if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
1752218893Sdim    NumElts = AT->getNumElements();
1753218893Sdim    EltTy = (NumElts == 0 ? 0 : AT->getElementType());
1754218893Sdim    return true;
1755218893Sdim  }
1756226890Sdim  if (StructType *ST = dyn_cast<StructType>(T)) {
1757218893Sdim    NumElts = ST->getNumContainedTypes();
1758218893Sdim    EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
1759218893Sdim    for (unsigned n = 1; n < NumElts; ++n) {
1760218893Sdim      if (ST->getContainedType(n) != EltTy)
1761218893Sdim        return false;
1762218893Sdim    }
1763218893Sdim    return true;
1764218893Sdim  }
1765218893Sdim  return false;
1766218893Sdim}
1767218893Sdim
1768218893Sdim/// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1769218893Sdim/// "homogeneous" aggregates with the same element type and number of elements.
1770226890Sdimstatic bool isCompatibleAggregate(Type *T1, Type *T2) {
1771218893Sdim  if (T1 == T2)
1772218893Sdim    return true;
1773218893Sdim
1774218893Sdim  unsigned NumElts1, NumElts2;
1775226890Sdim  Type *EltTy1, *EltTy2;
1776218893Sdim  if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1777218893Sdim      isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1778218893Sdim      NumElts1 == NumElts2 &&
1779218893Sdim      EltTy1 == EltTy2)
1780218893Sdim    return true;
1781218893Sdim
1782218893Sdim  return false;
1783218893Sdim}
1784218893Sdim
1785201360Srdivacky/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1786201360Srdivacky/// alloca or has an offset and size that corresponds to a component element
1787201360Srdivacky/// within it.  The offset checked here may have been formed from a GEP with a
1788201360Srdivacky/// pointer bitcasted to a different type.
1789218893Sdim///
1790218893Sdim/// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
1791218893Sdim/// unit.  If false, it only allows accesses known to be in a single element.
1792218893Sdimvoid SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
1793226890Sdim                           Type *MemOpType, bool isStore,
1794218893Sdim                           AllocaInfo &Info, Instruction *TheAccess,
1795218893Sdim                           bool AllowWholeAccess) {
1796201360Srdivacky  // Check if this is a load/store of the entire alloca.
1797218893Sdim  if (Offset == 0 && AllowWholeAccess &&
1798218893Sdim      MemSize == TD->getTypeAllocSize(Info.AI->getAllocatedType())) {
1799218893Sdim    // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1800218893Sdim    // loads/stores (which are essentially the same as the MemIntrinsics with
1801218893Sdim    // regard to copying padding between elements).  But, if an alloca is
1802218893Sdim    // flagged as both a source and destination of such operations, we'll need
1803218893Sdim    // to check later for padding between elements.
1804218893Sdim    if (!MemOpType || MemOpType->isIntegerTy()) {
1805218893Sdim      if (isStore)
1806218893Sdim        Info.isMemCpyDst = true;
1807218893Sdim      else
1808218893Sdim        Info.isMemCpySrc = true;
1809201360Srdivacky      return;
1810193323Sed    }
1811218893Sdim    // This is also safe for references using a type that is compatible with
1812218893Sdim    // the type of the alloca, so that loads/stores can be rewritten using
1813218893Sdim    // insertvalue/extractvalue.
1814218893Sdim    if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
1815218893Sdim      Info.hasSubelementAccess = true;
1816218893Sdim      return;
1817218893Sdim    }
1818193323Sed  }
1819201360Srdivacky  // Check if the offset/size correspond to a component within the alloca type.
1820226890Sdim  Type *T = Info.AI->getAllocatedType();
1821218893Sdim  if (TypeHasComponent(T, Offset, MemSize)) {
1822218893Sdim    Info.hasSubelementAccess = true;
1823201360Srdivacky    return;
1824218893Sdim  }
1825193323Sed
1826218893Sdim  return MarkUnsafe(Info, TheAccess);
1827193323Sed}
1828193323Sed
1829201360Srdivacky/// TypeHasComponent - Return true if T has a component type with the
1830201360Srdivacky/// specified offset and size.  If Size is zero, do not check the size.
1831226890Sdimbool SROA::TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size) {
1832226890Sdim  Type *EltTy;
1833201360Srdivacky  uint64_t EltSize;
1834226890Sdim  if (StructType *ST = dyn_cast<StructType>(T)) {
1835201360Srdivacky    const StructLayout *Layout = TD->getStructLayout(ST);
1836201360Srdivacky    unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1837201360Srdivacky    EltTy = ST->getContainedType(EltIdx);
1838201360Srdivacky    EltSize = TD->getTypeAllocSize(EltTy);
1839201360Srdivacky    Offset -= Layout->getElementOffset(EltIdx);
1840226890Sdim  } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
1841201360Srdivacky    EltTy = AT->getElementType();
1842201360Srdivacky    EltSize = TD->getTypeAllocSize(EltTy);
1843201360Srdivacky    if (Offset >= AT->getNumElements() * EltSize)
1844201360Srdivacky      return false;
1845201360Srdivacky    Offset %= EltSize;
1846245431Sdim  } else if (VectorType *VT = dyn_cast<VectorType>(T)) {
1847245431Sdim    EltTy = VT->getElementType();
1848245431Sdim    EltSize = TD->getTypeAllocSize(EltTy);
1849245431Sdim    if (Offset >= VT->getNumElements() * EltSize)
1850245431Sdim      return false;
1851245431Sdim    Offset %= EltSize;
1852201360Srdivacky  } else {
1853201360Srdivacky    return false;
1854193323Sed  }
1855201360Srdivacky  if (Offset == 0 && (Size == 0 || EltSize == Size))
1856201360Srdivacky    return true;
1857201360Srdivacky  // Check if the component spans multiple elements.
1858201360Srdivacky  if (Offset + Size > EltSize)
1859201360Srdivacky    return false;
1860201360Srdivacky  return TypeHasComponent(EltTy, Offset, Size);
1861193323Sed}
1862193323Sed
1863201360Srdivacky/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1864201360Srdivacky/// the instruction I, which references it, to use the separate elements.
1865201360Srdivacky/// Offset indicates the position within AI that is referenced by this
1866201360Srdivacky/// instruction.
1867201360Srdivackyvoid SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1868263509Sdim                                SmallVectorImpl<AllocaInst *> &NewElts) {
1869218893Sdim  for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
1870218893Sdim    Use &TheUse = UI.getUse();
1871218893Sdim    Instruction *User = cast<Instruction>(*UI++);
1872193323Sed
1873201360Srdivacky    if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1874201360Srdivacky      RewriteBitCast(BC, AI, Offset, NewElts);
1875218893Sdim      continue;
1876218893Sdim    }
1877245431Sdim
1878218893Sdim    if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1879201360Srdivacky      RewriteGEP(GEPI, AI, Offset, NewElts);
1880218893Sdim      continue;
1881218893Sdim    }
1882245431Sdim
1883218893Sdim    if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1884201360Srdivacky      ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1885201360Srdivacky      uint64_t MemSize = Length->getZExtValue();
1886201360Srdivacky      if (Offset == 0 &&
1887201360Srdivacky          MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1888201360Srdivacky        RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
1889201360Srdivacky      // Otherwise the intrinsic can only touch a single element and the
1890201360Srdivacky      // address operand will be updated, so nothing else needs to be done.
1891218893Sdim      continue;
1892218893Sdim    }
1893226890Sdim
1894226890Sdim    if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
1895226890Sdim      if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
1896226890Sdim          II->getIntrinsicID() == Intrinsic::lifetime_end) {
1897226890Sdim        RewriteLifetimeIntrinsic(II, AI, Offset, NewElts);
1898226890Sdim      }
1899226890Sdim      continue;
1900226890Sdim    }
1901245431Sdim
1902218893Sdim    if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1903226890Sdim      Type *LIType = LI->getType();
1904245431Sdim
1905218893Sdim      if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
1906201360Srdivacky        // Replace:
1907201360Srdivacky        //   %res = load { i32, i32 }* %alloc
1908201360Srdivacky        // with:
1909201360Srdivacky        //   %load.0 = load i32* %alloc.0
1910201360Srdivacky        //   %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1911201360Srdivacky        //   %load.1 = load i32* %alloc.1
1912201360Srdivacky        //   %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1913201360Srdivacky        // (Also works for arrays instead of structs)
1914201360Srdivacky        Value *Insert = UndefValue::get(LIType);
1915223017Sdim        IRBuilder<> Builder(LI);
1916201360Srdivacky        for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1917223017Sdim          Value *Load = Builder.CreateLoad(NewElts[i], "load");
1918223017Sdim          Insert = Builder.CreateInsertValue(Insert, Load, i, "insert");
1919201360Srdivacky        }
1920201360Srdivacky        LI->replaceAllUsesWith(Insert);
1921201360Srdivacky        DeadInsts.push_back(LI);
1922204642Srdivacky      } else if (LIType->isIntegerTy() &&
1923201360Srdivacky                 TD->getTypeAllocSize(LIType) ==
1924201360Srdivacky                 TD->getTypeAllocSize(AI->getAllocatedType())) {
1925201360Srdivacky        // If this is a load of the entire alloca to an integer, rewrite it.
1926201360Srdivacky        RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1927193323Sed      }
1928218893Sdim      continue;
1929218893Sdim    }
1930245431Sdim
1931218893Sdim    if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1932201360Srdivacky      Value *Val = SI->getOperand(0);
1933226890Sdim      Type *SIType = Val->getType();
1934218893Sdim      if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
1935201360Srdivacky        // Replace:
1936201360Srdivacky        //   store { i32, i32 } %val, { i32, i32 }* %alloc
1937201360Srdivacky        // with:
1938201360Srdivacky        //   %val.0 = extractvalue { i32, i32 } %val, 0
1939201360Srdivacky        //   store i32 %val.0, i32* %alloc.0
1940201360Srdivacky        //   %val.1 = extractvalue { i32, i32 } %val, 1
1941201360Srdivacky        //   store i32 %val.1, i32* %alloc.1
1942201360Srdivacky        // (Also works for arrays instead of structs)
1943223017Sdim        IRBuilder<> Builder(SI);
1944201360Srdivacky        for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1945223017Sdim          Value *Extract = Builder.CreateExtractValue(Val, i, Val->getName());
1946223017Sdim          Builder.CreateStore(Extract, NewElts[i]);
1947201360Srdivacky        }
1948201360Srdivacky        DeadInsts.push_back(SI);
1949204642Srdivacky      } else if (SIType->isIntegerTy() &&
1950201360Srdivacky                 TD->getTypeAllocSize(SIType) ==
1951201360Srdivacky                 TD->getTypeAllocSize(AI->getAllocatedType())) {
1952201360Srdivacky        // If this is a store of the entire alloca from an integer, rewrite it.
1953201360Srdivacky        RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1954193323Sed      }
1955218893Sdim      continue;
1956193323Sed    }
1957245431Sdim
1958218893Sdim    if (isa<SelectInst>(User) || isa<PHINode>(User)) {
1959245431Sdim      // If we have a PHI user of the alloca itself (as opposed to a GEP or
1960218893Sdim      // bitcast) we have to rewrite it.  GEP and bitcast uses will be RAUW'd to
1961218893Sdim      // the new pointer.
1962218893Sdim      if (!isa<AllocaInst>(I)) continue;
1963245431Sdim
1964218893Sdim      assert(Offset == 0 && NewElts[0] &&
1965218893Sdim             "Direct alloca use should have a zero offset");
1966245431Sdim
1967218893Sdim      // If we have a use of the alloca, we know the derived uses will be
1968218893Sdim      // utilizing just the first element of the scalarized result.  Insert a
1969218893Sdim      // bitcast of the first alloca before the user as required.
1970218893Sdim      AllocaInst *NewAI = NewElts[0];
1971218893Sdim      BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
1972218893Sdim      NewAI->moveBefore(BCI);
1973218893Sdim      TheUse = BCI;
1974218893Sdim      continue;
1975218893Sdim    }
1976193323Sed  }
1977193323Sed}
1978193323Sed
1979201360Srdivacky/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1980201360Srdivacky/// and recursively continue updating all of its uses.
1981201360Srdivackyvoid SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1982263509Sdim                          SmallVectorImpl<AllocaInst *> &NewElts) {
1983201360Srdivacky  RewriteForScalarRepl(BC, AI, Offset, NewElts);
1984201360Srdivacky  if (BC->getOperand(0) != AI)
1985201360Srdivacky    return;
1986193323Sed
1987201360Srdivacky  // The bitcast references the original alloca.  Replace its uses with
1988235633Sdim  // references to the alloca containing offset zero (which is normally at
1989235633Sdim  // index zero, but might not be in cases involving structs with elements
1990235633Sdim  // of size zero).
1991235633Sdim  Type *T = AI->getAllocatedType();
1992235633Sdim  uint64_t EltOffset = 0;
1993235633Sdim  Type *IdxTy;
1994235633Sdim  uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
1995235633Sdim  Instruction *Val = NewElts[Idx];
1996201360Srdivacky  if (Val->getType() != BC->getDestTy()) {
1997201360Srdivacky    Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1998201360Srdivacky    Val->takeName(BC);
1999201360Srdivacky  }
2000201360Srdivacky  BC->replaceAllUsesWith(Val);
2001201360Srdivacky  DeadInsts.push_back(BC);
2002201360Srdivacky}
2003193323Sed
2004201360Srdivacky/// FindElementAndOffset - Return the index of the element containing Offset
2005201360Srdivacky/// within the specified type, which must be either a struct or an array.
2006201360Srdivacky/// Sets T to the type of the element and Offset to the offset within that
2007201360Srdivacky/// element.  IdxTy is set to the type of the index result to be used in a
2008201360Srdivacky/// GEP instruction.
2009226890Sdimuint64_t SROA::FindElementAndOffset(Type *&T, uint64_t &Offset,
2010226890Sdim                                    Type *&IdxTy) {
2011201360Srdivacky  uint64_t Idx = 0;
2012226890Sdim  if (StructType *ST = dyn_cast<StructType>(T)) {
2013201360Srdivacky    const StructLayout *Layout = TD->getStructLayout(ST);
2014201360Srdivacky    Idx = Layout->getElementContainingOffset(Offset);
2015201360Srdivacky    T = ST->getContainedType(Idx);
2016201360Srdivacky    Offset -= Layout->getElementOffset(Idx);
2017201360Srdivacky    IdxTy = Type::getInt32Ty(T->getContext());
2018201360Srdivacky    return Idx;
2019245431Sdim  } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
2020245431Sdim    T = AT->getElementType();
2021245431Sdim    uint64_t EltSize = TD->getTypeAllocSize(T);
2022245431Sdim    Idx = Offset / EltSize;
2023245431Sdim    Offset -= Idx * EltSize;
2024245431Sdim    IdxTy = Type::getInt64Ty(T->getContext());
2025245431Sdim    return Idx;
2026193323Sed  }
2027245431Sdim  VectorType *VT = cast<VectorType>(T);
2028245431Sdim  T = VT->getElementType();
2029201360Srdivacky  uint64_t EltSize = TD->getTypeAllocSize(T);
2030201360Srdivacky  Idx = Offset / EltSize;
2031201360Srdivacky  Offset -= Idx * EltSize;
2032201360Srdivacky  IdxTy = Type::getInt64Ty(T->getContext());
2033201360Srdivacky  return Idx;
2034193323Sed}
2035193323Sed
2036201360Srdivacky/// RewriteGEP - Check if this GEP instruction moves the pointer across
2037201360Srdivacky/// elements of the alloca that are being split apart, and if so, rewrite
2038201360Srdivacky/// the GEP to be relative to the new element.
2039201360Srdivackyvoid SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
2040263509Sdim                      SmallVectorImpl<AllocaInst *> &NewElts) {
2041201360Srdivacky  uint64_t OldOffset = Offset;
2042201360Srdivacky  SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
2043245431Sdim  // If the GEP was dynamic then it must have been a dynamic vector lookup.
2044245431Sdim  // In this case, it must be the last GEP operand which is dynamic so keep that
2045245431Sdim  // aside until we've found the constant GEP offset then add it back in at the
2046245431Sdim  // end.
2047245431Sdim  Value* NonConstantIdx = 0;
2048245431Sdim  if (!GEPI->hasAllConstantIndices())
2049245431Sdim    NonConstantIdx = Indices.pop_back_val();
2050226890Sdim  Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
2051201360Srdivacky
2052201360Srdivacky  RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
2053201360Srdivacky
2054226890Sdim  Type *T = AI->getAllocatedType();
2055226890Sdim  Type *IdxTy;
2056201360Srdivacky  uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
2057201360Srdivacky  if (GEPI->getOperand(0) == AI)
2058201360Srdivacky    OldIdx = ~0ULL; // Force the GEP to be rewritten.
2059201360Srdivacky
2060201360Srdivacky  T = AI->getAllocatedType();
2061201360Srdivacky  uint64_t EltOffset = Offset;
2062201360Srdivacky  uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
2063201360Srdivacky
2064201360Srdivacky  // If this GEP does not move the pointer across elements of the alloca
2065201360Srdivacky  // being split, then it does not needs to be rewritten.
2066201360Srdivacky  if (Idx == OldIdx)
2067201360Srdivacky    return;
2068201360Srdivacky
2069226890Sdim  Type *i32Ty = Type::getInt32Ty(AI->getContext());
2070201360Srdivacky  SmallVector<Value*, 8> NewArgs;
2071201360Srdivacky  NewArgs.push_back(Constant::getNullValue(i32Ty));
2072201360Srdivacky  while (EltOffset != 0) {
2073201360Srdivacky    uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
2074201360Srdivacky    NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
2075201360Srdivacky  }
2076245431Sdim  if (NonConstantIdx) {
2077245431Sdim    Type* GepTy = T;
2078245431Sdim    // This GEP has a dynamic index.  We need to add "i32 0" to index through
2079245431Sdim    // any structs or arrays in the original type until we get to the vector
2080245431Sdim    // to index.
2081245431Sdim    while (!isa<VectorType>(GepTy)) {
2082245431Sdim      NewArgs.push_back(Constant::getNullValue(i32Ty));
2083245431Sdim      GepTy = cast<CompositeType>(GepTy)->getTypeAtIndex(0U);
2084245431Sdim    }
2085245431Sdim    NewArgs.push_back(NonConstantIdx);
2086245431Sdim  }
2087201360Srdivacky  Instruction *Val = NewElts[Idx];
2088201360Srdivacky  if (NewArgs.size() > 1) {
2089226890Sdim    Val = GetElementPtrInst::CreateInBounds(Val, NewArgs, "", GEPI);
2090201360Srdivacky    Val->takeName(GEPI);
2091201360Srdivacky  }
2092201360Srdivacky  if (Val->getType() != GEPI->getType())
2093203954Srdivacky    Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
2094201360Srdivacky  GEPI->replaceAllUsesWith(Val);
2095201360Srdivacky  DeadInsts.push_back(GEPI);
2096201360Srdivacky}
2097201360Srdivacky
2098226890Sdim/// RewriteLifetimeIntrinsic - II is a lifetime.start/lifetime.end. Rewrite it
2099226890Sdim/// to mark the lifetime of the scalarized memory.
2100226890Sdimvoid SROA::RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
2101226890Sdim                                    uint64_t Offset,
2102263509Sdim                                    SmallVectorImpl<AllocaInst *> &NewElts) {
2103226890Sdim  ConstantInt *OldSize = cast<ConstantInt>(II->getArgOperand(0));
2104226890Sdim  // Put matching lifetime markers on everything from Offset up to
2105226890Sdim  // Offset+OldSize.
2106226890Sdim  Type *AIType = AI->getAllocatedType();
2107226890Sdim  uint64_t NewOffset = Offset;
2108226890Sdim  Type *IdxTy;
2109226890Sdim  uint64_t Idx = FindElementAndOffset(AIType, NewOffset, IdxTy);
2110226890Sdim
2111226890Sdim  IRBuilder<> Builder(II);
2112226890Sdim  uint64_t Size = OldSize->getLimitedValue();
2113226890Sdim
2114226890Sdim  if (NewOffset) {
2115226890Sdim    // Splice the first element and index 'NewOffset' bytes in.  SROA will
2116226890Sdim    // split the alloca again later.
2117226890Sdim    Value *V = Builder.CreateBitCast(NewElts[Idx], Builder.getInt8PtrTy());
2118226890Sdim    V = Builder.CreateGEP(V, Builder.getInt64(NewOffset));
2119226890Sdim
2120226890Sdim    IdxTy = NewElts[Idx]->getAllocatedType();
2121226890Sdim    uint64_t EltSize = TD->getTypeAllocSize(IdxTy) - NewOffset;
2122226890Sdim    if (EltSize > Size) {
2123226890Sdim      EltSize = Size;
2124226890Sdim      Size = 0;
2125226890Sdim    } else {
2126226890Sdim      Size -= EltSize;
2127226890Sdim    }
2128226890Sdim    if (II->getIntrinsicID() == Intrinsic::lifetime_start)
2129226890Sdim      Builder.CreateLifetimeStart(V, Builder.getInt64(EltSize));
2130226890Sdim    else
2131226890Sdim      Builder.CreateLifetimeEnd(V, Builder.getInt64(EltSize));
2132226890Sdim    ++Idx;
2133226890Sdim  }
2134226890Sdim
2135226890Sdim  for (; Idx != NewElts.size() && Size; ++Idx) {
2136226890Sdim    IdxTy = NewElts[Idx]->getAllocatedType();
2137226890Sdim    uint64_t EltSize = TD->getTypeAllocSize(IdxTy);
2138226890Sdim    if (EltSize > Size) {
2139226890Sdim      EltSize = Size;
2140226890Sdim      Size = 0;
2141226890Sdim    } else {
2142226890Sdim      Size -= EltSize;
2143226890Sdim    }
2144226890Sdim    if (II->getIntrinsicID() == Intrinsic::lifetime_start)
2145226890Sdim      Builder.CreateLifetimeStart(NewElts[Idx],
2146226890Sdim                                  Builder.getInt64(EltSize));
2147226890Sdim    else
2148226890Sdim      Builder.CreateLifetimeEnd(NewElts[Idx],
2149226890Sdim                                Builder.getInt64(EltSize));
2150226890Sdim  }
2151226890Sdim  DeadInsts.push_back(II);
2152226890Sdim}
2153226890Sdim
2154193323Sed/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
2155193323Sed/// Rewrite it to copy or set the elements of the scalarized memory.
2156263509Sdimvoid
2157263509SdimSROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
2158263509Sdim                                   AllocaInst *AI,
2159263509Sdim                                   SmallVectorImpl<AllocaInst *> &NewElts) {
2160193323Sed  // If this is a memcpy/memmove, construct the other pointer as the
2161193323Sed  // appropriate type.  The "Other" pointer is the pointer that goes to memory
2162193323Sed  // that doesn't have anything to do with the alloca that we are promoting. For
2163193323Sed  // memset, this Value* stays null.
2164193323Sed  Value *OtherPtr = 0;
2165193323Sed  unsigned MemAlignment = MI->getAlignment();
2166193323Sed  if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
2167201360Srdivacky    if (Inst == MTI->getRawDest())
2168193323Sed      OtherPtr = MTI->getRawSource();
2169193323Sed    else {
2170201360Srdivacky      assert(Inst == MTI->getRawSource());
2171193323Sed      OtherPtr = MTI->getRawDest();
2172193323Sed    }
2173193323Sed  }
2174200581Srdivacky
2175193323Sed  // If there is an other pointer, we want to convert it to the same pointer
2176193323Sed  // type as AI has, so we can GEP through it safely.
2177193323Sed  if (OtherPtr) {
2178210299Sed    unsigned AddrSpace =
2179210299Sed      cast<PointerType>(OtherPtr->getType())->getAddressSpace();
2180201360Srdivacky
2181201360Srdivacky    // Remove bitcasts and all-zero GEPs from OtherPtr.  This is an
2182201360Srdivacky    // optimization, but it's also required to detect the corner case where
2183201360Srdivacky    // both pointer operands are referencing the same memory, and where
2184201360Srdivacky    // OtherPtr may be a bitcast or GEP that currently being rewritten.  (This
2185201360Srdivacky    // function is only called for mem intrinsics that access the whole
2186201360Srdivacky    // aggregate, so non-zero GEPs are not an issue here.)
2187210299Sed    OtherPtr = OtherPtr->stripPointerCasts();
2188218893Sdim
2189202878Srdivacky    // Copying the alloca to itself is a no-op: just delete it.
2190202878Srdivacky    if (OtherPtr == AI || OtherPtr == NewElts[0]) {
2191202878Srdivacky      // This code will run twice for a no-op memcpy -- once for each operand.
2192202878Srdivacky      // Put only one reference to MI on the DeadInsts list.
2193263509Sdim      for (SmallVectorImpl<Value *>::const_iterator I = DeadInsts.begin(),
2194202878Srdivacky             E = DeadInsts.end(); I != E; ++I)
2195202878Srdivacky        if (*I == MI) return;
2196202878Srdivacky      DeadInsts.push_back(MI);
2197201360Srdivacky      return;
2198202878Srdivacky    }
2199218893Sdim
2200193323Sed    // If the pointer is not the right type, insert a bitcast to the right
2201193323Sed    // type.
2202226890Sdim    Type *NewTy =
2203210299Sed      PointerType::get(AI->getType()->getElementType(), AddrSpace);
2204218893Sdim
2205210299Sed    if (OtherPtr->getType() != NewTy)
2206210299Sed      OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
2207193323Sed  }
2208218893Sdim
2209193323Sed  // Process each element of the aggregate.
2210201360Srdivacky  bool SROADest = MI->getRawDest() == Inst;
2211218893Sdim
2212198090Srdivacky  Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
2213193323Sed
2214193323Sed  for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2215193323Sed    // If this is a memcpy/memmove, emit a GEP of the other element address.
2216193323Sed    Value *OtherElt = 0;
2217193323Sed    unsigned OtherEltAlign = MemAlignment;
2218218893Sdim
2219202878Srdivacky    if (OtherPtr) {
2220198090Srdivacky      Value *Idx[2] = { Zero,
2221198090Srdivacky                      ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
2222226890Sdim      OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx,
2223203954Srdivacky                                              OtherPtr->getName()+"."+Twine(i),
2224201360Srdivacky                                                   MI);
2225193323Sed      uint64_t EltOffset;
2226226890Sdim      PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
2227226890Sdim      Type *OtherTy = OtherPtrTy->getElementType();
2228226890Sdim      if (StructType *ST = dyn_cast<StructType>(OtherTy)) {
2229193323Sed        EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
2230193323Sed      } else {
2231226890Sdim        Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
2232193323Sed        EltOffset = TD->getTypeAllocSize(EltTy)*i;
2233193323Sed      }
2234218893Sdim
2235193323Sed      // The alignment of the other pointer is the guaranteed alignment of the
2236193323Sed      // element, which is affected by both the known alignment of the whole
2237193323Sed      // mem intrinsic and the alignment of the element.  If the alignment of
2238193323Sed      // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
2239193323Sed      // known alignment is just 4 bytes.
2240193323Sed      OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
2241193323Sed    }
2242218893Sdim
2243193323Sed    Value *EltPtr = NewElts[i];
2244226890Sdim    Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
2245218893Sdim
2246193323Sed    // If we got down to a scalar, insert a load or store as appropriate.
2247193323Sed    if (EltTy->isSingleValueType()) {
2248193323Sed      if (isa<MemTransferInst>(MI)) {
2249193323Sed        if (SROADest) {
2250193323Sed          // From Other to Alloca.
2251193323Sed          Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
2252193323Sed          new StoreInst(Elt, EltPtr, MI);
2253193323Sed        } else {
2254193323Sed          // From Alloca to Other.
2255193323Sed          Value *Elt = new LoadInst(EltPtr, "tmp", MI);
2256193323Sed          new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
2257193323Sed        }
2258193323Sed        continue;
2259193323Sed      }
2260193323Sed      assert(isa<MemSetInst>(MI));
2261218893Sdim
2262193323Sed      // If the stored element is zero (common case), just store a null
2263193323Sed      // constant.
2264193323Sed      Constant *StoreVal;
2265210299Sed      if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
2266193323Sed        if (CI->isZero()) {
2267198090Srdivacky          StoreVal = Constant::getNullValue(EltTy);  // 0.0, null, 0, <0,0>
2268193323Sed        } else {
2269193323Sed          // If EltTy is a vector type, get the element type.
2270226890Sdim          Type *ValTy = EltTy->getScalarType();
2271194612Sed
2272193323Sed          // Construct an integer with the right value.
2273193323Sed          unsigned EltSize = TD->getTypeSizeInBits(ValTy);
2274193323Sed          APInt OneVal(EltSize, CI->getZExtValue());
2275193323Sed          APInt TotalVal(OneVal);
2276193323Sed          // Set each byte.
2277193323Sed          for (unsigned i = 0; 8*i < EltSize; ++i) {
2278193323Sed            TotalVal = TotalVal.shl(8);
2279193323Sed            TotalVal |= OneVal;
2280193323Sed          }
2281218893Sdim
2282193323Sed          // Convert the integer value to the appropriate type.
2283207618Srdivacky          StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
2284204642Srdivacky          if (ValTy->isPointerTy())
2285198090Srdivacky            StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
2286203954Srdivacky          else if (ValTy->isFloatingPointTy())
2287198090Srdivacky            StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
2288193323Sed          assert(StoreVal->getType() == ValTy && "Type mismatch!");
2289218893Sdim
2290193323Sed          // If the requested value was a vector constant, create it.
2291226890Sdim          if (EltTy->isVectorTy()) {
2292226890Sdim            unsigned NumElts = cast<VectorType>(EltTy)->getNumElements();
2293235633Sdim            StoreVal = ConstantVector::getSplat(NumElts, StoreVal);
2294193323Sed          }
2295193323Sed        }
2296193323Sed        new StoreInst(StoreVal, EltPtr, MI);
2297193323Sed        continue;
2298193323Sed      }
2299193323Sed      // Otherwise, if we're storing a byte variable, use a memset call for
2300193323Sed      // this element.
2301193323Sed    }
2302218893Sdim
2303193323Sed    unsigned EltSize = TD->getTypeAllocSize(EltTy);
2304235633Sdim    if (!EltSize)
2305235633Sdim      continue;
2306218893Sdim
2307218893Sdim    IRBuilder<> Builder(MI);
2308218893Sdim
2309193323Sed    // Finally, insert the meminst for this element.
2310218893Sdim    if (isa<MemSetInst>(MI)) {
2311218893Sdim      Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
2312218893Sdim                           MI->isVolatile());
2313193323Sed    } else {
2314218893Sdim      assert(isa<MemTransferInst>(MI));
2315218893Sdim      Value *Dst = SROADest ? EltPtr : OtherElt;  // Dest ptr
2316218893Sdim      Value *Src = SROADest ? OtherElt : EltPtr;  // Src ptr
2317218893Sdim
2318218893Sdim      if (isa<MemCpyInst>(MI))
2319218893Sdim        Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
2320218893Sdim      else
2321218893Sdim        Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
2322193323Sed    }
2323193323Sed  }
2324201360Srdivacky  DeadInsts.push_back(MI);
2325193323Sed}
2326193323Sed
2327200581Srdivacky/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
2328193323Sed/// overwrites the entire allocation.  Extract out the pieces of the stored
2329193323Sed/// integer and store them individually.
2330263509Sdimvoid
2331263509SdimSROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
2332263509Sdim                                    SmallVectorImpl<AllocaInst *> &NewElts) {
2333193323Sed  // Extract each element out of the integer according to its structure offset
2334193323Sed  // and store the element value to the individual alloca.
2335193323Sed  Value *SrcVal = SI->getOperand(0);
2336226890Sdim  Type *AllocaEltTy = AI->getAllocatedType();
2337193323Sed  uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
2338218893Sdim
2339218893Sdim  IRBuilder<> Builder(SI);
2340245431Sdim
2341193323Sed  // Handle tail padding by extending the operand
2342193323Sed  if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
2343218893Sdim    SrcVal = Builder.CreateZExt(SrcVal,
2344218893Sdim                            IntegerType::get(SI->getContext(), AllocaSizeBits));
2345193323Sed
2346202375Srdivacky  DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
2347198090Srdivacky               << '\n');
2348193323Sed
2349193323Sed  // There are two forms here: AI could be an array or struct.  Both cases
2350193323Sed  // have different ways to compute the element offset.
2351226890Sdim  if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2352193323Sed    const StructLayout *Layout = TD->getStructLayout(EltSTy);
2353218893Sdim
2354193323Sed    for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2355193323Sed      // Get the number of bits to shift SrcVal to get the value.
2356226890Sdim      Type *FieldTy = EltSTy->getElementType(i);
2357193323Sed      uint64_t Shift = Layout->getElementOffsetInBits(i);
2358218893Sdim
2359193323Sed      if (TD->isBigEndian())
2360193323Sed        Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
2361218893Sdim
2362193323Sed      Value *EltVal = SrcVal;
2363193323Sed      if (Shift) {
2364198090Srdivacky        Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
2365218893Sdim        EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
2366193323Sed      }
2367218893Sdim
2368193323Sed      // Truncate down to an integer of the right size.
2369193323Sed      uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
2370218893Sdim
2371193323Sed      // Ignore zero sized fields like {}, they obviously contain no data.
2372193323Sed      if (FieldSizeBits == 0) continue;
2373218893Sdim
2374193323Sed      if (FieldSizeBits != AllocaSizeBits)
2375218893Sdim        EltVal = Builder.CreateTrunc(EltVal,
2376218893Sdim                             IntegerType::get(SI->getContext(), FieldSizeBits));
2377193323Sed      Value *DestField = NewElts[i];
2378193323Sed      if (EltVal->getType() == FieldTy) {
2379193323Sed        // Storing to an integer field of this size, just do it.
2380204642Srdivacky      } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
2381193323Sed        // Bitcast to the right element type (for fp/vector values).
2382218893Sdim        EltVal = Builder.CreateBitCast(EltVal, FieldTy);
2383193323Sed      } else {
2384193323Sed        // Otherwise, bitcast the dest pointer (for aggregates).
2385218893Sdim        DestField = Builder.CreateBitCast(DestField,
2386218893Sdim                                     PointerType::getUnqual(EltVal->getType()));
2387193323Sed      }
2388193323Sed      new StoreInst(EltVal, DestField, SI);
2389193323Sed    }
2390218893Sdim
2391193323Sed  } else {
2392226890Sdim    ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
2393226890Sdim    Type *ArrayEltTy = ATy->getElementType();
2394193323Sed    uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
2395193323Sed    uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
2396193323Sed
2397193323Sed    uint64_t Shift;
2398218893Sdim
2399193323Sed    if (TD->isBigEndian())
2400193323Sed      Shift = AllocaSizeBits-ElementOffset;
2401218893Sdim    else
2402193323Sed      Shift = 0;
2403218893Sdim
2404193323Sed    for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2405193323Sed      // Ignore zero sized fields like {}, they obviously contain no data.
2406193323Sed      if (ElementSizeBits == 0) continue;
2407218893Sdim
2408193323Sed      Value *EltVal = SrcVal;
2409193323Sed      if (Shift) {
2410198090Srdivacky        Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
2411218893Sdim        EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
2412193323Sed      }
2413218893Sdim
2414193323Sed      // Truncate down to an integer of the right size.
2415193323Sed      if (ElementSizeBits != AllocaSizeBits)
2416218893Sdim        EltVal = Builder.CreateTrunc(EltVal,
2417218893Sdim                                     IntegerType::get(SI->getContext(),
2418218893Sdim                                                      ElementSizeBits));
2419193323Sed      Value *DestField = NewElts[i];
2420193323Sed      if (EltVal->getType() == ArrayEltTy) {
2421193323Sed        // Storing to an integer field of this size, just do it.
2422203954Srdivacky      } else if (ArrayEltTy->isFloatingPointTy() ||
2423204642Srdivacky                 ArrayEltTy->isVectorTy()) {
2424193323Sed        // Bitcast to the right element type (for fp/vector values).
2425218893Sdim        EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
2426193323Sed      } else {
2427193323Sed        // Otherwise, bitcast the dest pointer (for aggregates).
2428218893Sdim        DestField = Builder.CreateBitCast(DestField,
2429218893Sdim                                     PointerType::getUnqual(EltVal->getType()));
2430193323Sed      }
2431193323Sed      new StoreInst(EltVal, DestField, SI);
2432218893Sdim
2433193323Sed      if (TD->isBigEndian())
2434193323Sed        Shift -= ElementOffset;
2435218893Sdim      else
2436193323Sed        Shift += ElementOffset;
2437193323Sed    }
2438193323Sed  }
2439218893Sdim
2440201360Srdivacky  DeadInsts.push_back(SI);
2441193323Sed}
2442193323Sed
2443200581Srdivacky/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
2444193323Sed/// an integer.  Load the individual pieces to form the aggregate value.
2445263509Sdimvoid
2446263509SdimSROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
2447263509Sdim                                   SmallVectorImpl<AllocaInst *> &NewElts) {
2448193323Sed  // Extract each element out of the NewElts according to its structure offset
2449193323Sed  // and form the result value.
2450226890Sdim  Type *AllocaEltTy = AI->getAllocatedType();
2451193323Sed  uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
2452218893Sdim
2453202375Srdivacky  DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
2454198090Srdivacky               << '\n');
2455218893Sdim
2456193323Sed  // There are two forms here: AI could be an array or struct.  Both cases
2457193323Sed  // have different ways to compute the element offset.
2458193323Sed  const StructLayout *Layout = 0;
2459193323Sed  uint64_t ArrayEltBitOffset = 0;
2460226890Sdim  if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2461193323Sed    Layout = TD->getStructLayout(EltSTy);
2462193323Sed  } else {
2463226890Sdim    Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
2464193323Sed    ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
2465218893Sdim  }
2466218893Sdim
2467218893Sdim  Value *ResultVal =
2468198090Srdivacky    Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
2469218893Sdim
2470193323Sed  for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2471193323Sed    // Load the value from the alloca.  If the NewElt is an aggregate, cast
2472193323Sed    // the pointer to an integer of the same size before doing the load.
2473193323Sed    Value *SrcField = NewElts[i];
2474226890Sdim    Type *FieldTy =
2475193323Sed      cast<PointerType>(SrcField->getType())->getElementType();
2476193323Sed    uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
2477218893Sdim
2478193323Sed    // Ignore zero sized fields like {}, they obviously contain no data.
2479193323Sed    if (FieldSizeBits == 0) continue;
2480218893Sdim
2481226890Sdim    IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
2482198090Srdivacky                                                     FieldSizeBits);
2483204642Srdivacky    if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
2484204642Srdivacky        !FieldTy->isVectorTy())
2485195340Sed      SrcField = new BitCastInst(SrcField,
2486198090Srdivacky                                 PointerType::getUnqual(FieldIntTy),
2487193323Sed                                 "", LI);
2488193323Sed    SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
2489193323Sed
2490193323Sed    // If SrcField is a fp or vector of the right size but that isn't an
2491193323Sed    // integer type, bitcast to an integer so we can shift it.
2492193323Sed    if (SrcField->getType() != FieldIntTy)
2493193323Sed      SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
2494193323Sed
2495193323Sed    // Zero extend the field to be the same size as the final alloca so that
2496193323Sed    // we can shift and insert it.
2497193323Sed    if (SrcField->getType() != ResultVal->getType())
2498193323Sed      SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
2499218893Sdim
2500193323Sed    // Determine the number of bits to shift SrcField.
2501193323Sed    uint64_t Shift;
2502193323Sed    if (Layout) // Struct case.
2503193323Sed      Shift = Layout->getElementOffsetInBits(i);
2504193323Sed    else  // Array case.
2505193323Sed      Shift = i*ArrayEltBitOffset;
2506218893Sdim
2507193323Sed    if (TD->isBigEndian())
2508193323Sed      Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
2509218893Sdim
2510193323Sed    if (Shift) {
2511198090Srdivacky      Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
2512193323Sed      SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
2513193323Sed    }
2514193323Sed
2515210299Sed    // Don't create an 'or x, 0' on the first iteration.
2516210299Sed    if (!isa<Constant>(ResultVal) ||
2517210299Sed        !cast<Constant>(ResultVal)->isNullValue())
2518210299Sed      ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
2519210299Sed    else
2520210299Sed      ResultVal = SrcField;
2521193323Sed  }
2522193323Sed
2523193323Sed  // Handle tail padding by truncating the result
2524193323Sed  if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
2525193323Sed    ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
2526193323Sed
2527193323Sed  LI->replaceAllUsesWith(ResultVal);
2528201360Srdivacky  DeadInsts.push_back(LI);
2529193323Sed}
2530193323Sed
2531193323Sed/// HasPadding - Return true if the specified type has any structure or
2532218893Sdim/// alignment padding in between the elements that would be split apart
2533218893Sdim/// by SROA; return false otherwise.
2534245431Sdimstatic bool HasPadding(Type *Ty, const DataLayout &TD) {
2535226890Sdim  if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2536218893Sdim    Ty = ATy->getElementType();
2537218893Sdim    return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
2538218893Sdim  }
2539193323Sed
2540218893Sdim  // SROA currently handles only Arrays and Structs.
2541226890Sdim  StructType *STy = cast<StructType>(Ty);
2542218893Sdim  const StructLayout *SL = TD.getStructLayout(STy);
2543218893Sdim  unsigned PrevFieldBitOffset = 0;
2544218893Sdim  for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2545218893Sdim    unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
2546193323Sed
2547218893Sdim    // Check to see if there is any padding between this element and the
2548218893Sdim    // previous one.
2549218893Sdim    if (i) {
2550218893Sdim      unsigned PrevFieldEnd =
2551193323Sed        PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
2552218893Sdim      if (PrevFieldEnd < FieldBitOffset)
2553193323Sed        return true;
2554193323Sed    }
2555218893Sdim    PrevFieldBitOffset = FieldBitOffset;
2556193323Sed  }
2557218893Sdim  // Check for tail padding.
2558218893Sdim  if (unsigned EltCount = STy->getNumElements()) {
2559218893Sdim    unsigned PrevFieldEnd = PrevFieldBitOffset +
2560218893Sdim      TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
2561218893Sdim    if (PrevFieldEnd < SL->getSizeInBits())
2562218893Sdim      return true;
2563218893Sdim  }
2564218893Sdim  return false;
2565193323Sed}
2566193323Sed
2567193323Sed/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
2568193323Sed/// an aggregate can be broken down into elements.  Return 0 if not, 3 if safe,
2569193323Sed/// or 1 if safe after canonicalization has been performed.
2570202878Srdivackybool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
2571193323Sed  // Loop over the use list of the alloca.  We can only transform it if all of
2572193323Sed  // the users are safe to transform.
2573218893Sdim  AllocaInfo Info(AI);
2574218893Sdim
2575218893Sdim  isSafeForScalarRepl(AI, 0, Info);
2576201360Srdivacky  if (Info.isUnsafe) {
2577202375Srdivacky    DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
2578202878Srdivacky    return false;
2579193323Sed  }
2580218893Sdim
2581193323Sed  // Okay, we know all the users are promotable.  If the aggregate is a memcpy
2582193323Sed  // source and destination, we have to be careful.  In particular, the memcpy
2583193323Sed  // could be moving around elements that live in structure padding of the LLVM
2584193323Sed  // types, but may actually be used.  In these cases, we refuse to promote the
2585193323Sed  // struct.
2586193323Sed  if (Info.isMemCpySrc && Info.isMemCpyDst &&
2587201360Srdivacky      HasPadding(AI->getAllocatedType(), *TD))
2588202878Srdivacky    return false;
2589193323Sed
2590218893Sdim  // If the alloca never has an access to just *part* of it, but is accessed
2591218893Sdim  // via loads and stores, then we should use ConvertToScalarInfo to promote
2592218893Sdim  // the alloca instead of promoting each piece at a time and inserting fission
2593218893Sdim  // and fusion code.
2594218893Sdim  if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
2595218893Sdim    // If the struct/array just has one element, use basic SRoA.
2596226890Sdim    if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
2597218893Sdim      if (ST->getNumElements() > 1) return false;
2598218893Sdim    } else {
2599218893Sdim      if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
2600218893Sdim        return false;
2601218893Sdim    }
2602218893Sdim  }
2603193323Sed
2604193323Sed  return true;
2605193323Sed}
2606