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