1 //===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
20 //===----------------------------------------------------------------------===//
22 #define DEBUG_TYPE "scalarrepl"
23 #include "llvm/Transforms/Scalar.h"
24 #include "llvm/Constants.h"
25 #include "llvm/DIBuilder.h"
26 #include "llvm/DebugInfo.h"
27 #include "llvm/DerivedTypes.h"
28 #include "llvm/Function.h"
29 #include "llvm/GlobalVariable.h"
30 #include "llvm/IRBuilder.h"
31 #include "llvm/Instructions.h"
32 #include "llvm/IntrinsicInst.h"
33 #include "llvm/LLVMContext.h"
34 #include "llvm/Module.h"
35 #include "llvm/Operator.h"
36 #include "llvm/Pass.h"
37 #include "llvm/ADT/SetVector.h"
38 #include "llvm/ADT/SmallVector.h"
39 #include "llvm/ADT/Statistic.h"
40 #include "llvm/Analysis/Dominators.h"
41 #include "llvm/Analysis/Loads.h"
42 #include "llvm/Analysis/ValueTracking.h"
43 #include "llvm/Support/CallSite.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/GetElementPtrTypeIterator.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/Target/TargetData.h"
50 #include "llvm/Transforms/Utils/Local.h"
51 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
52 #include "llvm/Transforms/Utils/SSAUpdater.h"
55 STATISTIC(NumReplaced, "Number of allocas broken up");
56 STATISTIC(NumPromoted, "Number of allocas promoted");
57 STATISTIC(NumAdjusted, "Number of scalar allocas adjusted to allow promotion");
58 STATISTIC(NumConverted, "Number of aggregates converted to scalar");
59 STATISTIC(NumGlobals, "Number of allocas copied from constant global");
62 struct SROA : public FunctionPass {
63 SROA(int T, bool hasDT, char &ID, int ST, int AT, int SLT)
64 : FunctionPass(ID), HasDomTree(hasDT) {
70 StructMemberThreshold = 32;
72 StructMemberThreshold = ST;
74 ArrayElementThreshold = 8;
76 ArrayElementThreshold = AT;
78 // Do not limit the scalar integer load size if no threshold is given.
79 ScalarLoadThreshold = -1;
81 ScalarLoadThreshold = SLT;
84 bool runOnFunction(Function &F);
86 bool performScalarRepl(Function &F);
87 bool performPromotion(Function &F);
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;
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.
101 /// The alloca to promote.
104 /// CheckedPHIs - This is a set of verified PHI nodes, to prevent infinite
105 /// looping and avoid redundant work.
106 SmallPtrSet<PHINode*, 8> CheckedPHIs;
108 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
111 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
112 bool isMemCpySrc : 1;
114 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
115 bool isMemCpyDst : 1;
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;
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
125 bool hasALoadOrStore : 1;
127 explicit AllocaInfo(AllocaInst *ai)
128 : AI(ai), isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
129 hasSubelementAccess(false), hasALoadOrStore(false) {}
132 /// SRThreshold - The maximum alloca size to considered for SROA.
133 unsigned SRThreshold;
135 /// StructMemberThreshold - The maximum number of members a struct can
136 /// contain to be considered for SROA.
137 unsigned StructMemberThreshold;
139 /// ArrayElementThreshold - The maximum number of elements an array can
140 /// have to be considered for SROA.
141 unsigned ArrayElementThreshold;
143 /// ScalarLoadThreshold - The maximum size in bits of scalars to load when
144 /// converting to scalar
145 unsigned ScalarLoadThreshold;
147 void MarkUnsafe(AllocaInfo &I, Instruction *User) {
149 DEBUG(dbgs() << " Transformation preventing inst: " << *User << '\n');
152 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
154 void isSafeForScalarRepl(Instruction *I, uint64_t Offset, AllocaInfo &Info);
155 void isSafePHISelectUseForScalarRepl(Instruction *User, uint64_t Offset,
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,
165 void DoScalarReplacement(AllocaInst *AI,
166 std::vector<AllocaInst*> &WorkList);
167 void DeleteDeadInstructions();
169 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
170 SmallVector<AllocaInst*, 32> &NewElts);
171 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
172 SmallVector<AllocaInst*, 32> &NewElts);
173 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
174 SmallVector<AllocaInst*, 32> &NewElts);
175 void RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
177 SmallVector<AllocaInst*, 32> &NewElts);
178 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
180 SmallVector<AllocaInst*, 32> &NewElts);
181 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
182 SmallVector<AllocaInst*, 32> &NewElts);
183 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
184 SmallVector<AllocaInst*, 32> &NewElts);
185 bool ShouldAttemptScalarRepl(AllocaInst *AI);
187 static MemTransferInst *isOnlyCopiedFromConstantGlobal(
188 AllocaInst *AI, SmallVector<Instruction*, 4> &ToDelete);
191 // SROA_DT - SROA that uses DominatorTree.
192 struct SROA_DT : public SROA {
195 SROA_DT(int T = -1, int ST = -1, int AT = -1, int SLT = -1) :
196 SROA(T, true, ID, ST, AT, SLT) {
197 initializeSROA_DTPass(*PassRegistry::getPassRegistry());
200 // getAnalysisUsage - This pass does not require any passes, but we know it
201 // will not alter the CFG, so say so.
202 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
203 AU.addRequired<DominatorTree>();
204 AU.setPreservesCFG();
208 // SROA_SSAUp - SROA that uses SSAUpdater.
209 struct SROA_SSAUp : public SROA {
212 SROA_SSAUp(int T = -1, int ST = -1, int AT = -1, int SLT = -1) :
213 SROA(T, false, ID, ST, AT, SLT) {
214 initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
217 // getAnalysisUsage - This pass does not require any passes, but we know it
218 // will not alter the CFG, so say so.
219 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
220 AU.setPreservesCFG();
226 char SROA_DT::ID = 0;
227 char SROA_SSAUp::ID = 0;
229 INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl",
230 "Scalar Replacement of Aggregates (DT)", false, false)
231 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
232 INITIALIZE_PASS_END(SROA_DT, "scalarrepl",
233 "Scalar Replacement of Aggregates (DT)", false, false)
235 INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
236 "Scalar Replacement of Aggregates (SSAUp)", false, false)
237 INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
238 "Scalar Replacement of Aggregates (SSAUp)", false, false)
240 // Public interface to the ScalarReplAggregates pass
241 FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
243 int StructMemberThreshold,
244 int ArrayElementThreshold,
245 int ScalarLoadThreshold) {
247 return new SROA_DT(Threshold, StructMemberThreshold, ArrayElementThreshold,
248 ScalarLoadThreshold);
249 return new SROA_SSAUp(Threshold, StructMemberThreshold,
250 ArrayElementThreshold, ScalarLoadThreshold);
254 //===----------------------------------------------------------------------===//
255 // Convert To Scalar Optimization.
256 //===----------------------------------------------------------------------===//
259 /// ConvertToScalarInfo - This class implements the "Convert To Scalar"
260 /// optimization, which scans the uses of an alloca and determines if it can
261 /// rewrite it in terms of a single new alloca that can be mem2reg'd.
262 class ConvertToScalarInfo {
263 /// AllocaSize - The size of the alloca being considered in bytes.
265 const TargetData &TD;
266 unsigned ScalarLoadThreshold;
268 /// IsNotTrivial - This is set to true if there is some access to the object
269 /// which means that mem2reg can't promote it.
272 /// ScalarKind - Tracks the kind of alloca being considered for promotion,
273 /// computed based on the uses of the alloca rather than the LLVM type system.
277 // Accesses via GEPs that are consistent with element access of a vector
278 // type. This will not be converted into a vector unless there is a later
279 // access using an actual vector type.
282 // Accesses via vector operations and GEPs that are consistent with the
283 // layout of a vector type.
286 // An integer bag-of-bits with bitwise operations for insertion and
287 // extraction. Any combination of types can be converted into this kind
292 /// VectorTy - This tracks the type that we should promote the vector to if
293 /// it is possible to turn it into a vector. This starts out null, and if it
294 /// isn't possible to turn into a vector type, it gets set to VoidTy.
295 VectorType *VectorTy;
297 /// HadNonMemTransferAccess - True if there is at least one access to the
298 /// alloca that is not a MemTransferInst. We don't want to turn structs into
299 /// large integers unless there is some potential for optimization.
300 bool HadNonMemTransferAccess;
302 /// HadDynamicAccess - True if some element of this alloca was dynamic.
303 /// We don't yet have support for turning a dynamic access into a large
305 bool HadDynamicAccess;
308 explicit ConvertToScalarInfo(unsigned Size, const TargetData &td,
310 : AllocaSize(Size), TD(td), ScalarLoadThreshold(SLT), IsNotTrivial(false),
311 ScalarKind(Unknown), VectorTy(0), HadNonMemTransferAccess(false),
312 HadDynamicAccess(false) { }
314 AllocaInst *TryConvert(AllocaInst *AI);
317 bool CanConvertToScalar(Value *V, uint64_t Offset, Value* NonConstantIdx);
318 void MergeInTypeForLoadOrStore(Type *In, uint64_t Offset);
319 bool MergeInVectorType(VectorType *VInTy, uint64_t Offset);
320 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset,
321 Value *NonConstantIdx);
323 Value *ConvertScalar_ExtractValue(Value *NV, Type *ToType,
324 uint64_t Offset, Value* NonConstantIdx,
325 IRBuilder<> &Builder);
326 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
327 uint64_t Offset, Value* NonConstantIdx,
328 IRBuilder<> &Builder);
330 } // end anonymous namespace.
333 /// TryConvert - Analyze the specified alloca, and if it is safe to do so,
334 /// rewrite it to be a new alloca which is mem2reg'able. This returns the new
335 /// alloca if possible or null if not.
336 AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
337 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
339 if (!CanConvertToScalar(AI, 0, 0) || !IsNotTrivial)
342 // If an alloca has only memset / memcpy uses, it may still have an Unknown
343 // ScalarKind. Treat it as an Integer below.
344 if (ScalarKind == Unknown)
345 ScalarKind = Integer;
347 if (ScalarKind == Vector && VectorTy->getBitWidth() != AllocaSize * 8)
348 ScalarKind = Integer;
350 // If we were able to find a vector type that can handle this with
351 // insert/extract elements, and if there was at least one use that had
352 // a vector type, promote this to a vector. We don't want to promote
353 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
354 // we just get a lot of insert/extracts. If at least one vector is
355 // involved, then we probably really do have a union of vector/array.
357 if (ScalarKind == Vector) {
358 assert(VectorTy && "Missing type for vector scalar.");
359 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
360 << *VectorTy << '\n');
361 NewTy = VectorTy; // Use the vector type.
363 unsigned BitWidth = AllocaSize * 8;
365 // Do not convert to scalar integer if the alloca size exceeds the
366 // scalar load threshold.
367 if (BitWidth > ScalarLoadThreshold)
370 if ((ScalarKind == ImplicitVector || ScalarKind == Integer) &&
371 !HadNonMemTransferAccess && !TD.fitsInLegalInteger(BitWidth))
373 // Dynamic accesses on integers aren't yet supported. They need us to shift
374 // by a dynamic amount which could be difficult to work out as we might not
375 // know whether to use a left or right shift.
376 if (ScalarKind == Integer && HadDynamicAccess)
379 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
380 // Create and insert the integer alloca.
381 NewTy = IntegerType::get(AI->getContext(), BitWidth);
383 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
384 ConvertUsesToScalar(AI, NewAI, 0, 0);
388 /// MergeInTypeForLoadOrStore - Add the 'In' type to the accumulated vector type
389 /// (VectorTy) so far at the offset specified by Offset (which is specified in
392 /// There are two cases we handle here:
393 /// 1) A union of vector types of the same size and potentially its elements.
394 /// Here we turn element accesses into insert/extract element operations.
395 /// This promotes a <4 x float> with a store of float to the third element
396 /// into a <4 x float> that uses insert element.
397 /// 2) A fully general blob of memory, which we turn into some (potentially
398 /// large) integer type with extract and insert operations where the loads
399 /// and stores would mutate the memory. We mark this by setting VectorTy
401 void ConvertToScalarInfo::MergeInTypeForLoadOrStore(Type *In,
403 // If we already decided to turn this into a blob of integer memory, there is
404 // nothing to be done.
405 if (ScalarKind == Integer)
408 // If this could be contributing to a vector, analyze it.
410 // If the In type is a vector that is the same size as the alloca, see if it
411 // matches the existing VecTy.
412 if (VectorType *VInTy = dyn_cast<VectorType>(In)) {
413 if (MergeInVectorType(VInTy, Offset))
415 } else if (In->isFloatTy() || In->isDoubleTy() ||
416 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
417 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
418 // Full width accesses can be ignored, because they can always be turned
420 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
421 if (EltSize == AllocaSize)
424 // If we're accessing something that could be an element of a vector, see
425 // if the implied vector agrees with what we already have and if Offset is
426 // compatible with it.
427 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
428 (!VectorTy || EltSize == VectorTy->getElementType()
429 ->getPrimitiveSizeInBits()/8)) {
431 ScalarKind = ImplicitVector;
432 VectorTy = VectorType::get(In, AllocaSize/EltSize);
438 // Otherwise, we have a case that we can't handle with an optimized vector
439 // form. We can still turn this into a large integer.
440 ScalarKind = Integer;
443 /// MergeInVectorType - Handles the vector case of MergeInTypeForLoadOrStore,
444 /// returning true if the type was successfully merged and false otherwise.
445 bool ConvertToScalarInfo::MergeInVectorType(VectorType *VInTy,
447 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
448 // If we're storing/loading a vector of the right size, allow it as a
449 // vector. If this the first vector we see, remember the type so that
450 // we know the element size. If this is a subsequent access, ignore it
451 // even if it is a differing type but the same size. Worst case we can
452 // bitcast the resultant vectors.
462 /// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
463 /// its accesses to a single vector type, return true and set VecTy to
464 /// the new type. If we could convert the alloca into a single promotable
465 /// integer, return true but set VecTy to VoidTy. Further, if the use is not a
466 /// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
467 /// is the current offset from the base of the alloca being analyzed.
469 /// If we see at least one access to the value that is as a vector type, set the
471 bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset,
472 Value* NonConstantIdx) {
473 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
474 Instruction *User = cast<Instruction>(*UI);
476 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
477 // Don't break volatile loads.
480 // Don't touch MMX operations.
481 if (LI->getType()->isX86_MMXTy())
483 HadNonMemTransferAccess = true;
484 MergeInTypeForLoadOrStore(LI->getType(), Offset);
488 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
489 // Storing the pointer, not into the value?
490 if (SI->getOperand(0) == V || !SI->isSimple()) return false;
491 // Don't touch MMX operations.
492 if (SI->getOperand(0)->getType()->isX86_MMXTy())
494 HadNonMemTransferAccess = true;
495 MergeInTypeForLoadOrStore(SI->getOperand(0)->getType(), Offset);
499 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
500 if (!onlyUsedByLifetimeMarkers(BCI))
501 IsNotTrivial = true; // Can't be mem2reg'd.
502 if (!CanConvertToScalar(BCI, Offset, NonConstantIdx))
507 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
508 // If this is a GEP with a variable indices, we can't handle it.
509 PointerType* PtrTy = dyn_cast<PointerType>(GEP->getPointerOperandType());
513 // Compute the offset that this GEP adds to the pointer.
514 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
515 Value *GEPNonConstantIdx = 0;
516 if (!GEP->hasAllConstantIndices()) {
517 if (!isa<VectorType>(PtrTy->getElementType()))
521 GEPNonConstantIdx = Indices.pop_back_val();
522 if (!GEPNonConstantIdx->getType()->isIntegerTy(32))
524 HadDynamicAccess = true;
526 GEPNonConstantIdx = NonConstantIdx;
527 uint64_t GEPOffset = TD.getIndexedOffset(PtrTy,
529 // See if all uses can be converted.
530 if (!CanConvertToScalar(GEP, Offset+GEPOffset, GEPNonConstantIdx))
532 IsNotTrivial = true; // Can't be mem2reg'd.
533 HadNonMemTransferAccess = true;
537 // If this is a constant sized memset of a constant value (e.g. 0) we can
539 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
540 // Store to dynamic index.
543 // Store of constant value.
544 if (!isa<ConstantInt>(MSI->getValue()))
547 // Store of constant size.
548 ConstantInt *Len = dyn_cast<ConstantInt>(MSI->getLength());
552 // If the size differs from the alloca, we can only convert the alloca to
553 // an integer bag-of-bits.
554 // FIXME: This should handle all of the cases that are currently accepted
555 // as vector element insertions.
556 if (Len->getZExtValue() != AllocaSize || Offset != 0)
557 ScalarKind = Integer;
559 IsNotTrivial = true; // Can't be mem2reg'd.
560 HadNonMemTransferAccess = true;
564 // If this is a memcpy or memmove into or out of the whole allocation, we
565 // can handle it like a load or store of the scalar type.
566 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
567 // Store to dynamic index.
570 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
571 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
574 IsNotTrivial = true; // Can't be mem2reg'd.
578 // If this is a lifetime intrinsic, we can handle it.
579 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
580 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
581 II->getIntrinsicID() == Intrinsic::lifetime_end) {
586 // Otherwise, we cannot handle this!
593 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
594 /// directly. This happens when we are converting an "integer union" to a
595 /// single integer scalar, or when we are converting a "vector union" to a
596 /// vector with insert/extractelement instructions.
598 /// Offset is an offset from the original alloca, in bits that need to be
599 /// shifted to the right. By the end of this, there should be no uses of Ptr.
600 void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
602 Value* NonConstantIdx) {
603 while (!Ptr->use_empty()) {
604 Instruction *User = cast<Instruction>(Ptr->use_back());
606 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
607 ConvertUsesToScalar(CI, NewAI, Offset, NonConstantIdx);
608 CI->eraseFromParent();
612 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
613 // Compute the offset that this GEP adds to the pointer.
614 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
615 Value* GEPNonConstantIdx = 0;
616 if (!GEP->hasAllConstantIndices()) {
617 assert(!NonConstantIdx &&
618 "Dynamic GEP reading from dynamic GEP unsupported");
619 GEPNonConstantIdx = Indices.pop_back_val();
621 GEPNonConstantIdx = NonConstantIdx;
622 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
624 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8, GEPNonConstantIdx);
625 GEP->eraseFromParent();
629 IRBuilder<> Builder(User);
631 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
632 // The load is a bit extract from NewAI shifted right by Offset bits.
633 Value *LoadedVal = Builder.CreateLoad(NewAI);
635 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset,
636 NonConstantIdx, Builder);
637 LI->replaceAllUsesWith(NewLoadVal);
638 LI->eraseFromParent();
642 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
643 assert(SI->getOperand(0) != Ptr && "Consistency error!");
644 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
645 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
646 NonConstantIdx, Builder);
647 Builder.CreateStore(New, NewAI);
648 SI->eraseFromParent();
650 // If the load we just inserted is now dead, then the inserted store
651 // overwrote the entire thing.
652 if (Old->use_empty())
653 Old->eraseFromParent();
657 // If this is a constant sized memset of a constant value (e.g. 0) we can
658 // transform it into a store of the expanded constant value.
659 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
660 assert(MSI->getRawDest() == Ptr && "Consistency error!");
661 assert(!NonConstantIdx && "Cannot replace dynamic memset with insert");
662 int64_t SNumBytes = cast<ConstantInt>(MSI->getLength())->getSExtValue();
663 if (SNumBytes > 0 && (SNumBytes >> 32) == 0) {
664 unsigned NumBytes = static_cast<unsigned>(SNumBytes);
665 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
667 // Compute the value replicated the right number of times.
668 APInt APVal(NumBytes*8, Val);
670 // Splat the value if non-zero.
672 for (unsigned i = 1; i != NumBytes; ++i)
675 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
676 Value *New = ConvertScalar_InsertValue(
677 ConstantInt::get(User->getContext(), APVal),
678 Old, Offset, 0, Builder);
679 Builder.CreateStore(New, NewAI);
681 // If the load we just inserted is now dead, then the memset overwrote
683 if (Old->use_empty())
684 Old->eraseFromParent();
686 MSI->eraseFromParent();
690 // If this is a memcpy or memmove into or out of the whole allocation, we
691 // can handle it like a load or store of the scalar type.
692 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
693 assert(Offset == 0 && "must be store to start of alloca");
694 assert(!NonConstantIdx && "Cannot replace dynamic transfer with insert");
696 // If the source and destination are both to the same alloca, then this is
697 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
699 AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, &TD, 0));
701 if (GetUnderlyingObject(MTI->getSource(), &TD, 0) != OrigAI) {
702 // Dest must be OrigAI, change this to be a load from the original
703 // pointer (bitcasted), then a store to our new alloca.
704 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
705 Value *SrcPtr = MTI->getSource();
706 PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
707 PointerType* AIPTy = cast<PointerType>(NewAI->getType());
708 if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
709 AIPTy = PointerType::get(AIPTy->getElementType(),
710 SPTy->getAddressSpace());
712 SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
714 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
715 SrcVal->setAlignment(MTI->getAlignment());
716 Builder.CreateStore(SrcVal, NewAI);
717 } else if (GetUnderlyingObject(MTI->getDest(), &TD, 0) != OrigAI) {
718 // Src must be OrigAI, change this to be a load from NewAI then a store
719 // through the original dest pointer (bitcasted).
720 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
721 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
723 PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
724 PointerType* AIPTy = cast<PointerType>(NewAI->getType());
725 if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
726 AIPTy = PointerType::get(AIPTy->getElementType(),
727 DPTy->getAddressSpace());
729 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
731 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
732 NewStore->setAlignment(MTI->getAlignment());
734 // Noop transfer. Src == Dst
737 MTI->eraseFromParent();
741 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
742 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
743 II->getIntrinsicID() == Intrinsic::lifetime_end) {
744 // There's no need to preserve these, as the resulting alloca will be
745 // converted to a register anyways.
746 II->eraseFromParent();
751 llvm_unreachable("Unsupported operation!");
755 /// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
756 /// or vector value FromVal, extracting the bits from the offset specified by
757 /// Offset. This returns the value, which is of type ToType.
759 /// This happens when we are converting an "integer union" to a single
760 /// integer scalar, or when we are converting a "vector union" to a vector with
761 /// insert/extractelement instructions.
763 /// Offset is an offset from the original alloca, in bits that need to be
764 /// shifted to the right.
765 Value *ConvertToScalarInfo::
766 ConvertScalar_ExtractValue(Value *FromVal, Type *ToType,
767 uint64_t Offset, Value* NonConstantIdx,
768 IRBuilder<> &Builder) {
769 // If the load is of the whole new alloca, no conversion is needed.
770 Type *FromType = FromVal->getType();
771 if (FromType == ToType && Offset == 0)
774 // If the result alloca is a vector type, this is either an element
775 // access or a bitcast to another vector type of the same size.
776 if (VectorType *VTy = dyn_cast<VectorType>(FromType)) {
777 unsigned FromTypeSize = TD.getTypeAllocSize(FromType);
778 unsigned ToTypeSize = TD.getTypeAllocSize(ToType);
779 if (FromTypeSize == ToTypeSize)
780 return Builder.CreateBitCast(FromVal, ToType);
782 // Otherwise it must be an element access.
785 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
786 Elt = Offset/EltSize;
787 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
789 // Return the element extracted out of it.
791 if (NonConstantIdx) {
793 Idx = Builder.CreateAdd(NonConstantIdx,
794 Builder.getInt32(Elt),
797 Idx = NonConstantIdx;
799 Idx = Builder.getInt32(Elt);
800 Value *V = Builder.CreateExtractElement(FromVal, Idx);
801 if (V->getType() != ToType)
802 V = Builder.CreateBitCast(V, ToType);
806 // If ToType is a first class aggregate, extract out each of the pieces and
807 // use insertvalue's to form the FCA.
808 if (StructType *ST = dyn_cast<StructType>(ToType)) {
809 assert(!NonConstantIdx &&
810 "Dynamic indexing into struct types not supported");
811 const StructLayout &Layout = *TD.getStructLayout(ST);
812 Value *Res = UndefValue::get(ST);
813 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
814 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
815 Offset+Layout.getElementOffsetInBits(i),
817 Res = Builder.CreateInsertValue(Res, Elt, i);
822 if (ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
823 assert(!NonConstantIdx &&
824 "Dynamic indexing into array types not supported");
825 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
826 Value *Res = UndefValue::get(AT);
827 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
828 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
829 Offset+i*EltSize, 0, Builder);
830 Res = Builder.CreateInsertValue(Res, Elt, i);
835 // Otherwise, this must be a union that was converted to an integer value.
836 IntegerType *NTy = cast<IntegerType>(FromVal->getType());
838 // If this is a big-endian system and the load is narrower than the
839 // full alloca type, we need to do a shift to get the right bits.
841 if (TD.isBigEndian()) {
842 // On big-endian machines, the lowest bit is stored at the bit offset
843 // from the pointer given by getTypeStoreSizeInBits. This matters for
844 // integers with a bitwidth that is not a multiple of 8.
845 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
846 TD.getTypeStoreSizeInBits(ToType) - Offset;
851 // Note: we support negative bitwidths (with shl) which are not defined.
852 // We do this to support (f.e.) loads off the end of a structure where
853 // only some bits are used.
854 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
855 FromVal = Builder.CreateLShr(FromVal,
856 ConstantInt::get(FromVal->getType(), ShAmt));
857 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
858 FromVal = Builder.CreateShl(FromVal,
859 ConstantInt::get(FromVal->getType(), -ShAmt));
861 // Finally, unconditionally truncate the integer to the right width.
862 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
863 if (LIBitWidth < NTy->getBitWidth())
865 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
867 else if (LIBitWidth > NTy->getBitWidth())
869 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
872 // If the result is an integer, this is a trunc or bitcast.
873 if (ToType->isIntegerTy()) {
875 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
876 // Just do a bitcast, we know the sizes match up.
877 FromVal = Builder.CreateBitCast(FromVal, ToType);
879 // Otherwise must be a pointer.
880 FromVal = Builder.CreateIntToPtr(FromVal, ToType);
882 assert(FromVal->getType() == ToType && "Didn't convert right?");
886 /// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
887 /// or vector value "Old" at the offset specified by Offset.
889 /// This happens when we are converting an "integer union" to a
890 /// single integer scalar, or when we are converting a "vector union" to a
891 /// vector with insert/extractelement instructions.
893 /// Offset is an offset from the original alloca, in bits that need to be
894 /// shifted to the right.
896 /// NonConstantIdx is an index value if there was a GEP with a non-constant
897 /// index value. If this is 0 then all GEPs used to find this insert address
899 Value *ConvertToScalarInfo::
900 ConvertScalar_InsertValue(Value *SV, Value *Old,
901 uint64_t Offset, Value* NonConstantIdx,
902 IRBuilder<> &Builder) {
903 // Convert the stored type to the actual type, shift it left to insert
904 // then 'or' into place.
905 Type *AllocaType = Old->getType();
906 LLVMContext &Context = Old->getContext();
908 if (VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
909 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
910 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
912 // Changing the whole vector with memset or with an access of a different
914 if (ValSize == VecSize)
915 return Builder.CreateBitCast(SV, AllocaType);
917 // Must be an element insertion.
918 Type *EltTy = VTy->getElementType();
919 if (SV->getType() != EltTy)
920 SV = Builder.CreateBitCast(SV, EltTy);
921 uint64_t EltSize = TD.getTypeAllocSizeInBits(EltTy);
922 unsigned Elt = Offset/EltSize;
924 if (NonConstantIdx) {
926 Idx = Builder.CreateAdd(NonConstantIdx,
927 Builder.getInt32(Elt),
930 Idx = NonConstantIdx;
932 Idx = Builder.getInt32(Elt);
933 return Builder.CreateInsertElement(Old, SV, Idx);
936 // If SV is a first-class aggregate value, insert each value recursively.
937 if (StructType *ST = dyn_cast<StructType>(SV->getType())) {
938 assert(!NonConstantIdx &&
939 "Dynamic indexing into struct types not supported");
940 const StructLayout &Layout = *TD.getStructLayout(ST);
941 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
942 Value *Elt = Builder.CreateExtractValue(SV, i);
943 Old = ConvertScalar_InsertValue(Elt, Old,
944 Offset+Layout.getElementOffsetInBits(i),
950 if (ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
951 assert(!NonConstantIdx &&
952 "Dynamic indexing into array types not supported");
953 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
954 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
955 Value *Elt = Builder.CreateExtractValue(SV, i);
956 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, 0, Builder);
961 // If SV is a float, convert it to the appropriate integer type.
962 // If it is a pointer, do the same.
963 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
964 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
965 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
966 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
967 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
968 SV = Builder.CreateBitCast(SV, IntegerType::get(SV->getContext(),SrcWidth));
969 else if (SV->getType()->isPointerTy())
970 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()));
972 // Zero extend or truncate the value if needed.
973 if (SV->getType() != AllocaType) {
974 if (SV->getType()->getPrimitiveSizeInBits() <
975 AllocaType->getPrimitiveSizeInBits())
976 SV = Builder.CreateZExt(SV, AllocaType);
978 // Truncation may be needed if storing more than the alloca can hold
979 // (undefined behavior).
980 SV = Builder.CreateTrunc(SV, AllocaType);
981 SrcWidth = DestWidth;
982 SrcStoreWidth = DestStoreWidth;
986 // If this is a big-endian system and the store is narrower than the
987 // full alloca type, we need to do a shift to get the right bits.
989 if (TD.isBigEndian()) {
990 // On big-endian machines, the lowest bit is stored at the bit offset
991 // from the pointer given by getTypeStoreSizeInBits. This matters for
992 // integers with a bitwidth that is not a multiple of 8.
993 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
998 // Note: we support negative bitwidths (with shr) which are not defined.
999 // We do this to support (f.e.) stores off the end of a structure where
1000 // only some bits in the structure are set.
1001 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1002 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1003 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(), ShAmt));
1005 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1006 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(), -ShAmt));
1007 Mask = Mask.lshr(-ShAmt);
1010 // Mask out the bits we are about to insert from the old value, and or
1012 if (SrcWidth != DestWidth) {
1013 assert(DestWidth > SrcWidth);
1014 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
1015 SV = Builder.CreateOr(Old, SV, "ins");
1021 //===----------------------------------------------------------------------===//
1023 //===----------------------------------------------------------------------===//
1026 bool SROA::runOnFunction(Function &F) {
1027 TD = getAnalysisIfAvailable<TargetData>();
1029 bool Changed = performPromotion(F);
1031 // FIXME: ScalarRepl currently depends on TargetData more than it
1032 // theoretically needs to. It should be refactored in order to support
1033 // target-independent IR. Until this is done, just skip the actual
1034 // scalar-replacement portion of this pass.
1035 if (!TD) return Changed;
1038 bool LocalChange = performScalarRepl(F);
1039 if (!LocalChange) break; // No need to repromote if no scalarrepl
1041 LocalChange = performPromotion(F);
1042 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
1049 class AllocaPromoter : public LoadAndStorePromoter {
1052 SmallVector<DbgDeclareInst *, 4> DDIs;
1053 SmallVector<DbgValueInst *, 4> DVIs;
1055 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1057 : LoadAndStorePromoter(Insts, S), AI(0), DIB(DB) {}
1059 void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
1060 // Remember which alloca we're promoting (for isInstInList).
1062 if (MDNode *DebugNode = MDNode::getIfExists(AI->getContext(), AI)) {
1063 for (Value::use_iterator UI = DebugNode->use_begin(),
1064 E = DebugNode->use_end(); UI != E; ++UI)
1065 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
1066 DDIs.push_back(DDI);
1067 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
1068 DVIs.push_back(DVI);
1071 LoadAndStorePromoter::run(Insts);
1072 AI->eraseFromParent();
1073 for (SmallVector<DbgDeclareInst *, 4>::iterator I = DDIs.begin(),
1074 E = DDIs.end(); I != E; ++I) {
1075 DbgDeclareInst *DDI = *I;
1076 DDI->eraseFromParent();
1078 for (SmallVector<DbgValueInst *, 4>::iterator I = DVIs.begin(),
1079 E = DVIs.end(); I != E; ++I) {
1080 DbgValueInst *DVI = *I;
1081 DVI->eraseFromParent();
1085 virtual bool isInstInList(Instruction *I,
1086 const SmallVectorImpl<Instruction*> &Insts) const {
1087 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1088 return LI->getOperand(0) == AI;
1089 return cast<StoreInst>(I)->getPointerOperand() == AI;
1092 virtual void updateDebugInfo(Instruction *Inst) const {
1093 for (SmallVector<DbgDeclareInst *, 4>::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);
1101 for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
1102 E = DVIs.end(); I != E; ++I) {
1103 DbgValueInst *DVI = *I;
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));
1113 Arg = SI->getOperand(0);
1114 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1115 Arg = LI->getOperand(0);
1119 Instruction *DbgVal =
1120 DIB->insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1122 DbgVal->setDebugLoc(DVI->getDebugLoc());
1126 } // end anon namespace
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.
1132 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1133 /// %V = load i32* %P2
1135 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1136 /// %V2 = load i32* %Other
1137 /// %V = select i1 %cond, i32 %V1, i32 %V2
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 TargetData *TD) {
1142 bool TDerefable = SI->getTrueValue()->isDereferenceablePointer();
1143 bool FDerefable = SI->getFalseValue()->isDereferenceablePointer();
1145 for (Value::use_iterator UI = SI->use_begin(), UE = SI->use_end();
1147 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1148 if (LI == 0 || !LI->isSimple()) return false;
1150 // Both operands to the select need to be dereferencable, either absolutely
1151 // (e.g. allocas) or at this point because we can see other accesses to it.
1152 if (!TDerefable && !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
1153 LI->getAlignment(), TD))
1155 if (!FDerefable && !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
1156 LI->getAlignment(), TD))
1163 /// isSafePHIToSpeculate - PHI instructions that use an alloca and are
1164 /// subsequently loaded can be rewritten to load both input pointers in the pred
1165 /// blocks and then PHI the results, allowing the load of the alloca to be
1168 /// %P2 = phi [i32* %Alloca, i32* %Other]
1169 /// %V = load i32* %P2
1171 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1173 /// %V2 = load i32* %Other
1175 /// %V = phi [i32 %V1, i32 %V2]
1177 /// We can do this to a select if its only uses are loads and if the operand to
1178 /// the select can be loaded unconditionally.
1179 static bool isSafePHIToSpeculate(PHINode *PN, const TargetData *TD) {
1180 // For now, we can only do this promotion if the load is in the same block as
1181 // the PHI, and if there are no stores between the phi and load.
1182 // TODO: Allow recursive phi users.
1183 // TODO: Allow stores.
1184 BasicBlock *BB = PN->getParent();
1185 unsigned MaxAlign = 0;
1186 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
1188 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1189 if (LI == 0 || !LI->isSimple()) return false;
1191 // For now we only allow loads in the same block as the PHI. This is a
1192 // common case that happens when instcombine merges two loads through a PHI.
1193 if (LI->getParent() != BB) return false;
1195 // Ensure that there are no instructions between the PHI and the load that
1197 for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
1198 if (BBI->mayWriteToMemory())
1201 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1204 // Okay, we know that we have one or more loads in the same block as the PHI.
1205 // We can transform this if it is safe to push the loads into the predecessor
1206 // blocks. The only thing to watch out for is that we can't put a possibly
1207 // trapping load in the predecessor if it is a critical edge.
1208 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1209 BasicBlock *Pred = PN->getIncomingBlock(i);
1210 Value *InVal = PN->getIncomingValue(i);
1212 // If the terminator of the predecessor has side-effects (an invoke),
1213 // there is no safe place to put a load in the predecessor.
1214 if (Pred->getTerminator()->mayHaveSideEffects())
1217 // If the value is produced by the terminator of the predecessor
1218 // (an invoke), there is no valid place to put a load in the predecessor.
1219 if (Pred->getTerminator() == InVal)
1222 // If the predecessor has a single successor, then the edge isn't critical.
1223 if (Pred->getTerminator()->getNumSuccessors() == 1)
1226 // If this pointer is always safe to load, or if we can prove that there is
1227 // already a load in the block, then we can move the load to the pred block.
1228 if (InVal->isDereferenceablePointer() ||
1229 isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign, TD))
1239 /// tryToMakeAllocaBePromotable - This returns true if the alloca only has
1240 /// direct (non-volatile) loads and stores to it. If the alloca is close but
1241 /// not quite there, this will transform the code to allow promotion. As such,
1242 /// it is a non-pure predicate.
1243 static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const TargetData *TD) {
1244 SetVector<Instruction*, SmallVector<Instruction*, 4>,
1245 SmallPtrSet<Instruction*, 4> > InstsToRewrite;
1247 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
1250 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1251 if (!LI->isSimple())
1256 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1257 if (SI->getOperand(0) == AI || !SI->isSimple())
1258 return false; // Don't allow a store OF the AI, only INTO the AI.
1262 if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
1263 // If the condition being selected on is a constant, fold the select, yes
1264 // this does (rarely) happen early on.
1265 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
1266 Value *Result = SI->getOperand(1+CI->isZero());
1267 SI->replaceAllUsesWith(Result);
1268 SI->eraseFromParent();
1270 // This is very rare and we just scrambled the use list of AI, start
1272 return tryToMakeAllocaBePromotable(AI, TD);
1275 // If it is safe to turn "load (select c, AI, ptr)" into a select of two
1276 // loads, then we can transform this by rewriting the select.
1277 if (!isSafeSelectToSpeculate(SI, TD))
1280 InstsToRewrite.insert(SI);
1284 if (PHINode *PN = dyn_cast<PHINode>(U)) {
1285 if (PN->use_empty()) { // Dead PHIs can be stripped.
1286 InstsToRewrite.insert(PN);
1290 // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
1291 // in the pred blocks, then we can transform this by rewriting the PHI.
1292 if (!isSafePHIToSpeculate(PN, TD))
1295 InstsToRewrite.insert(PN);
1299 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
1300 if (onlyUsedByLifetimeMarkers(BCI)) {
1301 InstsToRewrite.insert(BCI);
1309 // If there are no instructions to rewrite, then all uses are load/stores and
1311 if (InstsToRewrite.empty())
1314 // If we have instructions that need to be rewritten for this to be promotable
1315 // take care of it now.
1316 for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
1317 if (BitCastInst *BCI = dyn_cast<BitCastInst>(InstsToRewrite[i])) {
1318 // This could only be a bitcast used by nothing but lifetime intrinsics.
1319 for (BitCastInst::use_iterator I = BCI->use_begin(), E = BCI->use_end();
1321 Use &U = I.getUse();
1323 cast<Instruction>(U.getUser())->eraseFromParent();
1325 BCI->eraseFromParent();
1329 if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
1330 // Selects in InstsToRewrite only have load uses. Rewrite each as two
1331 // loads with a new select.
1332 while (!SI->use_empty()) {
1333 LoadInst *LI = cast<LoadInst>(SI->use_back());
1335 IRBuilder<> Builder(LI);
1336 LoadInst *TrueLoad =
1337 Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t");
1338 LoadInst *FalseLoad =
1339 Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".f");
1341 // Transfer alignment and TBAA info if present.
1342 TrueLoad->setAlignment(LI->getAlignment());
1343 FalseLoad->setAlignment(LI->getAlignment());
1344 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1345 TrueLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1346 FalseLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1349 Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
1351 LI->replaceAllUsesWith(V);
1352 LI->eraseFromParent();
1355 // Now that all the loads are gone, the select is gone too.
1356 SI->eraseFromParent();
1360 // Otherwise, we have a PHI node which allows us to push the loads into the
1362 PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
1363 if (PN->use_empty()) {
1364 PN->eraseFromParent();
1368 Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
1369 PHINode *NewPN = PHINode::Create(LoadTy, PN->getNumIncomingValues(),
1370 PN->getName()+".ld", PN);
1372 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1373 // matter which one we get and if any differ, it doesn't matter.
1374 LoadInst *SomeLoad = cast<LoadInst>(PN->use_back());
1375 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1376 unsigned Align = SomeLoad->getAlignment();
1378 // Rewrite all loads of the PN to use the new PHI.
1379 while (!PN->use_empty()) {
1380 LoadInst *LI = cast<LoadInst>(PN->use_back());
1381 LI->replaceAllUsesWith(NewPN);
1382 LI->eraseFromParent();
1385 // Inject loads into all of the pred blocks. Keep track of which blocks we
1386 // insert them into in case we have multiple edges from the same block.
1387 DenseMap<BasicBlock*, LoadInst*> InsertedLoads;
1389 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1390 BasicBlock *Pred = PN->getIncomingBlock(i);
1391 LoadInst *&Load = InsertedLoads[Pred];
1393 Load = new LoadInst(PN->getIncomingValue(i),
1394 PN->getName() + "." + Pred->getName(),
1395 Pred->getTerminator());
1396 Load->setAlignment(Align);
1397 if (TBAATag) Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1400 NewPN->addIncoming(Load, Pred);
1403 PN->eraseFromParent();
1410 bool SROA::performPromotion(Function &F) {
1411 std::vector<AllocaInst*> Allocas;
1412 DominatorTree *DT = 0;
1414 DT = &getAnalysis<DominatorTree>();
1416 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
1417 DIBuilder DIB(*F.getParent());
1418 bool Changed = false;
1419 SmallVector<Instruction*, 64> Insts;
1423 // Find allocas that are safe to promote, by looking at all instructions in
1425 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
1426 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
1427 if (tryToMakeAllocaBePromotable(AI, TD))
1428 Allocas.push_back(AI);
1430 if (Allocas.empty()) break;
1433 PromoteMemToReg(Allocas, *DT);
1436 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
1437 AllocaInst *AI = Allocas[i];
1439 // Build list of instructions to promote.
1440 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1442 Insts.push_back(cast<Instruction>(*UI));
1443 AllocaPromoter(Insts, SSA, &DIB).run(AI, Insts);
1447 NumPromoted += Allocas.size();
1455 /// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
1456 /// SROA. It must be a struct or array type with a small number of elements.
1457 bool SROA::ShouldAttemptScalarRepl(AllocaInst *AI) {
1458 Type *T = AI->getAllocatedType();
1459 // Do not promote any struct that has too many members.
1460 if (StructType *ST = dyn_cast<StructType>(T))
1461 return ST->getNumElements() <= StructMemberThreshold;
1462 // Do not promote any array that has too many elements.
1463 if (ArrayType *AT = dyn_cast<ArrayType>(T))
1464 return AT->getNumElements() <= ArrayElementThreshold;
1468 /// getPointeeAlignment - Compute the minimum alignment of the value pointed
1469 /// to by the given pointer.
1470 static unsigned getPointeeAlignment(Value *V, const TargetData &TD) {
1471 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1472 if (CE->getOpcode() == Instruction::BitCast ||
1473 (CE->getOpcode() == Instruction::GetElementPtr &&
1474 cast<GEPOperator>(CE)->hasAllZeroIndices()))
1475 return getPointeeAlignment(CE->getOperand(0), TD);
1477 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1478 if (!GV->isDeclaration())
1479 return TD.getPreferredAlignment(GV);
1481 if (PointerType *PT = dyn_cast<PointerType>(V->getType()))
1482 return TD.getABITypeAlignment(PT->getElementType());
1488 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
1489 // which runs on all of the alloca instructions in the function, removing them
1490 // if they are only used by getelementptr instructions.
1492 bool SROA::performScalarRepl(Function &F) {
1493 std::vector<AllocaInst*> WorkList;
1495 // Scan the entry basic block, adding allocas to the worklist.
1496 BasicBlock &BB = F.getEntryBlock();
1497 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
1498 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
1499 WorkList.push_back(A);
1501 // Process the worklist
1502 bool Changed = false;
1503 while (!WorkList.empty()) {
1504 AllocaInst *AI = WorkList.back();
1505 WorkList.pop_back();
1507 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
1508 // with unused elements.
1509 if (AI->use_empty()) {
1510 AI->eraseFromParent();
1515 // If this alloca is impossible for us to promote, reject it early.
1516 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
1519 // Check to see if this allocation is only modified by a memcpy/memmove from
1520 // a constant global whose alignment is equal to or exceeds that of the
1521 // allocation. If this is the case, we can change all users to use
1522 // the constant global instead. This is commonly produced by the CFE by
1523 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
1524 // is only subsequently read.
1525 SmallVector<Instruction *, 4> ToDelete;
1526 if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(AI, ToDelete)) {
1527 if (AI->getAlignment() <= getPointeeAlignment(Copy->getSource(), *TD)) {
1528 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
1529 DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
1530 for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
1531 ToDelete[i]->eraseFromParent();
1532 Constant *TheSrc = cast<Constant>(Copy->getSource());
1533 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
1534 Copy->eraseFromParent(); // Don't mutate the global.
1535 AI->eraseFromParent();
1542 // Check to see if we can perform the core SROA transformation. We cannot
1543 // transform the allocation instruction if it is an array allocation
1544 // (allocations OF arrays are ok though), and an allocation of a scalar
1545 // value cannot be decomposed at all.
1546 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
1548 // Do not promote [0 x %struct].
1549 if (AllocaSize == 0) continue;
1551 // Do not promote any struct whose size is too big.
1552 if (AllocaSize > SRThreshold) continue;
1554 // If the alloca looks like a good candidate for scalar replacement, and if
1555 // all its users can be transformed, then split up the aggregate into its
1556 // separate elements.
1557 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
1558 DoScalarReplacement(AI, WorkList);
1563 // If we can turn this aggregate value (potentially with casts) into a
1564 // simple scalar value that can be mem2reg'd into a register value.
1565 // IsNotTrivial tracks whether this is something that mem2reg could have
1566 // promoted itself. If so, we don't want to transform it needlessly. Note
1567 // that we can't just check based on the type: the alloca may be of an i32
1568 // but that has pointer arithmetic to set byte 3 of it or something.
1569 if (AllocaInst *NewAI = ConvertToScalarInfo(
1570 (unsigned)AllocaSize, *TD, ScalarLoadThreshold).TryConvert(AI)) {
1571 NewAI->takeName(AI);
1572 AI->eraseFromParent();
1578 // Otherwise, couldn't process this alloca.
1584 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1585 /// predicate, do SROA now.
1586 void SROA::DoScalarReplacement(AllocaInst *AI,
1587 std::vector<AllocaInst*> &WorkList) {
1588 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
1589 SmallVector<AllocaInst*, 32> ElementAllocas;
1590 if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1591 ElementAllocas.reserve(ST->getNumContainedTypes());
1592 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
1593 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
1595 AI->getName() + "." + Twine(i), AI);
1596 ElementAllocas.push_back(NA);
1597 WorkList.push_back(NA); // Add to worklist for recursive processing
1600 ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
1601 ElementAllocas.reserve(AT->getNumElements());
1602 Type *ElTy = AT->getElementType();
1603 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1604 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
1605 AI->getName() + "." + Twine(i), AI);
1606 ElementAllocas.push_back(NA);
1607 WorkList.push_back(NA); // Add to worklist for recursive processing
1611 // Now that we have created the new alloca instructions, rewrite all the
1612 // uses of the old alloca.
1613 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
1615 // Now erase any instructions that were made dead while rewriting the alloca.
1616 DeleteDeadInstructions();
1617 AI->eraseFromParent();
1622 /// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1623 /// recursively including all their operands that become trivially dead.
1624 void SROA::DeleteDeadInstructions() {
1625 while (!DeadInsts.empty()) {
1626 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
1628 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1629 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1630 // Zero out the operand and see if it becomes trivially dead.
1631 // (But, don't add allocas to the dead instruction list -- they are
1632 // already on the worklist and will be deleted separately.)
1634 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1635 DeadInsts.push_back(U);
1638 I->eraseFromParent();
1642 /// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1643 /// performing scalar replacement of alloca AI. The results are flagged in
1644 /// the Info parameter. Offset indicates the position within AI that is
1645 /// referenced by this instruction.
1646 void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
1648 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1649 Instruction *User = cast<Instruction>(*UI);
1651 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1652 isSafeForScalarRepl(BC, Offset, Info);
1653 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1654 uint64_t GEPOffset = Offset;
1655 isSafeGEP(GEPI, GEPOffset, Info);
1657 isSafeForScalarRepl(GEPI, GEPOffset, Info);
1658 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1659 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1661 return MarkUnsafe(Info, User);
1662 if (Length->isNegative())
1663 return MarkUnsafe(Info, User);
1665 isSafeMemAccess(Offset, Length->getZExtValue(), 0,
1666 UI.getOperandNo() == 0, Info, MI,
1667 true /*AllowWholeAccess*/);
1668 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1669 if (!LI->isSimple())
1670 return MarkUnsafe(Info, User);
1671 Type *LIType = LI->getType();
1672 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
1673 LIType, false, Info, LI, true /*AllowWholeAccess*/);
1674 Info.hasALoadOrStore = true;
1676 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1677 // Store is ok if storing INTO the pointer, not storing the pointer
1678 if (!SI->isSimple() || SI->getOperand(0) == I)
1679 return MarkUnsafe(Info, User);
1681 Type *SIType = SI->getOperand(0)->getType();
1682 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
1683 SIType, true, Info, SI, true /*AllowWholeAccess*/);
1684 Info.hasALoadOrStore = true;
1685 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
1686 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1687 II->getIntrinsicID() != Intrinsic::lifetime_end)
1688 return MarkUnsafe(Info, User);
1689 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1690 isSafePHISelectUseForScalarRepl(User, Offset, Info);
1692 return MarkUnsafe(Info, User);
1694 if (Info.isUnsafe) return;
1699 /// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
1700 /// derived from the alloca, we can often still split the alloca into elements.
1701 /// This is useful if we have a large alloca where one element is phi'd
1702 /// together somewhere: we can SRoA and promote all the other elements even if
1703 /// we end up not being able to promote this one.
1705 /// All we require is that the uses of the PHI do not index into other parts of
1706 /// the alloca. The most important use case for this is single load and stores
1707 /// that are PHI'd together, which can happen due to code sinking.
1708 void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
1710 // If we've already checked this PHI, don't do it again.
1711 if (PHINode *PN = dyn_cast<PHINode>(I))
1712 if (!Info.CheckedPHIs.insert(PN))
1715 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1716 Instruction *User = cast<Instruction>(*UI);
1718 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1719 isSafePHISelectUseForScalarRepl(BC, Offset, Info);
1720 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1721 // Only allow "bitcast" GEPs for simplicity. We could generalize this,
1722 // but would have to prove that we're staying inside of an element being
1724 if (!GEPI->hasAllZeroIndices())
1725 return MarkUnsafe(Info, User);
1726 isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
1727 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1728 if (!LI->isSimple())
1729 return MarkUnsafe(Info, User);
1730 Type *LIType = LI->getType();
1731 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
1732 LIType, false, Info, LI, false /*AllowWholeAccess*/);
1733 Info.hasALoadOrStore = true;
1735 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1736 // Store is ok if storing INTO the pointer, not storing the pointer
1737 if (!SI->isSimple() || SI->getOperand(0) == I)
1738 return MarkUnsafe(Info, User);
1740 Type *SIType = SI->getOperand(0)->getType();
1741 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
1742 SIType, true, Info, SI, false /*AllowWholeAccess*/);
1743 Info.hasALoadOrStore = true;
1744 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1745 isSafePHISelectUseForScalarRepl(User, Offset, Info);
1747 return MarkUnsafe(Info, User);
1749 if (Info.isUnsafe) return;
1753 /// isSafeGEP - Check if a GEP instruction can be handled for scalar
1754 /// replacement. It is safe when all the indices are constant, in-bounds
1755 /// references, and when the resulting offset corresponds to an element within
1756 /// the alloca type. The results are flagged in the Info parameter. Upon
1757 /// return, Offset is adjusted as specified by the GEP indices.
1758 void SROA::isSafeGEP(GetElementPtrInst *GEPI,
1759 uint64_t &Offset, AllocaInfo &Info) {
1760 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1763 bool NonConstant = false;
1764 unsigned NonConstantIdxSize = 0;
1766 // Walk through the GEP type indices, checking the types that this indexes
1768 for (; GEPIt != E; ++GEPIt) {
1769 // Ignore struct elements, no extra checking needed for these.
1770 if ((*GEPIt)->isStructTy())
1773 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1775 // Non constant GEPs are only a problem on arrays, structs, and pointers
1776 // Vectors can be dynamically indexed.
1777 // FIXME: Add support for dynamic indexing on arrays. This should be
1778 // ok on any subarrays of the alloca array, eg, a[0][i] is ok, but a[i][0]
1780 if (!(*GEPIt)->isVectorTy())
1781 return MarkUnsafe(Info, GEPI);
1783 NonConstantIdxSize = TD->getTypeAllocSize(*GEPIt);
1787 // Compute the offset due to this GEP and check if the alloca has a
1788 // component element at that offset.
1789 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1790 // If this GEP is non constant then the last operand must have been a
1791 // dynamic index into a vector. Pop this now as it has no impact on the
1792 // constant part of the offset.
1795 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
1796 if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset,
1797 NonConstantIdxSize))
1798 MarkUnsafe(Info, GEPI);
1801 /// isHomogeneousAggregate - Check if type T is a struct or array containing
1802 /// elements of the same type (which is always true for arrays). If so,
1803 /// return true with NumElts and EltTy set to the number of elements and the
1804 /// element type, respectively.
1805 static bool isHomogeneousAggregate(Type *T, unsigned &NumElts,
1807 if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
1808 NumElts = AT->getNumElements();
1809 EltTy = (NumElts == 0 ? 0 : AT->getElementType());
1812 if (StructType *ST = dyn_cast<StructType>(T)) {
1813 NumElts = ST->getNumContainedTypes();
1814 EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
1815 for (unsigned n = 1; n < NumElts; ++n) {
1816 if (ST->getContainedType(n) != EltTy)
1824 /// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1825 /// "homogeneous" aggregates with the same element type and number of elements.
1826 static bool isCompatibleAggregate(Type *T1, Type *T2) {
1830 unsigned NumElts1, NumElts2;
1831 Type *EltTy1, *EltTy2;
1832 if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1833 isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1834 NumElts1 == NumElts2 &&
1841 /// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1842 /// alloca or has an offset and size that corresponds to a component element
1843 /// within it. The offset checked here may have been formed from a GEP with a
1844 /// pointer bitcasted to a different type.
1846 /// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
1847 /// unit. If false, it only allows accesses known to be in a single element.
1848 void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
1849 Type *MemOpType, bool isStore,
1850 AllocaInfo &Info, Instruction *TheAccess,
1851 bool AllowWholeAccess) {
1852 // Check if this is a load/store of the entire alloca.
1853 if (Offset == 0 && AllowWholeAccess &&
1854 MemSize == TD->getTypeAllocSize(Info.AI->getAllocatedType())) {
1855 // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1856 // loads/stores (which are essentially the same as the MemIntrinsics with
1857 // regard to copying padding between elements). But, if an alloca is
1858 // flagged as both a source and destination of such operations, we'll need
1859 // to check later for padding between elements.
1860 if (!MemOpType || MemOpType->isIntegerTy()) {
1862 Info.isMemCpyDst = true;
1864 Info.isMemCpySrc = true;
1867 // This is also safe for references using a type that is compatible with
1868 // the type of the alloca, so that loads/stores can be rewritten using
1869 // insertvalue/extractvalue.
1870 if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
1871 Info.hasSubelementAccess = true;
1875 // Check if the offset/size correspond to a component within the alloca type.
1876 Type *T = Info.AI->getAllocatedType();
1877 if (TypeHasComponent(T, Offset, MemSize)) {
1878 Info.hasSubelementAccess = true;
1882 return MarkUnsafe(Info, TheAccess);
1885 /// TypeHasComponent - Return true if T has a component type with the
1886 /// specified offset and size. If Size is zero, do not check the size.
1887 bool SROA::TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size) {
1890 if (StructType *ST = dyn_cast<StructType>(T)) {
1891 const StructLayout *Layout = TD->getStructLayout(ST);
1892 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1893 EltTy = ST->getContainedType(EltIdx);
1894 EltSize = TD->getTypeAllocSize(EltTy);
1895 Offset -= Layout->getElementOffset(EltIdx);
1896 } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
1897 EltTy = AT->getElementType();
1898 EltSize = TD->getTypeAllocSize(EltTy);
1899 if (Offset >= AT->getNumElements() * EltSize)
1902 } else if (VectorType *VT = dyn_cast<VectorType>(T)) {
1903 EltTy = VT->getElementType();
1904 EltSize = TD->getTypeAllocSize(EltTy);
1905 if (Offset >= VT->getNumElements() * EltSize)
1911 if (Offset == 0 && (Size == 0 || EltSize == Size))
1913 // Check if the component spans multiple elements.
1914 if (Offset + Size > EltSize)
1916 return TypeHasComponent(EltTy, Offset, Size);
1919 /// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1920 /// the instruction I, which references it, to use the separate elements.
1921 /// Offset indicates the position within AI that is referenced by this
1923 void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1924 SmallVector<AllocaInst*, 32> &NewElts) {
1925 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
1926 Use &TheUse = UI.getUse();
1927 Instruction *User = cast<Instruction>(*UI++);
1929 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1930 RewriteBitCast(BC, AI, Offset, NewElts);
1934 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1935 RewriteGEP(GEPI, AI, Offset, NewElts);
1939 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1940 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1941 uint64_t MemSize = Length->getZExtValue();
1943 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1944 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
1945 // Otherwise the intrinsic can only touch a single element and the
1946 // address operand will be updated, so nothing else needs to be done.
1950 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
1951 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
1952 II->getIntrinsicID() == Intrinsic::lifetime_end) {
1953 RewriteLifetimeIntrinsic(II, AI, Offset, NewElts);
1958 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1959 Type *LIType = LI->getType();
1961 if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
1963 // %res = load { i32, i32 }* %alloc
1965 // %load.0 = load i32* %alloc.0
1966 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1967 // %load.1 = load i32* %alloc.1
1968 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1969 // (Also works for arrays instead of structs)
1970 Value *Insert = UndefValue::get(LIType);
1971 IRBuilder<> Builder(LI);
1972 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1973 Value *Load = Builder.CreateLoad(NewElts[i], "load");
1974 Insert = Builder.CreateInsertValue(Insert, Load, i, "insert");
1976 LI->replaceAllUsesWith(Insert);
1977 DeadInsts.push_back(LI);
1978 } else if (LIType->isIntegerTy() &&
1979 TD->getTypeAllocSize(LIType) ==
1980 TD->getTypeAllocSize(AI->getAllocatedType())) {
1981 // If this is a load of the entire alloca to an integer, rewrite it.
1982 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1987 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1988 Value *Val = SI->getOperand(0);
1989 Type *SIType = Val->getType();
1990 if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
1992 // store { i32, i32 } %val, { i32, i32 }* %alloc
1994 // %val.0 = extractvalue { i32, i32 } %val, 0
1995 // store i32 %val.0, i32* %alloc.0
1996 // %val.1 = extractvalue { i32, i32 } %val, 1
1997 // store i32 %val.1, i32* %alloc.1
1998 // (Also works for arrays instead of structs)
1999 IRBuilder<> Builder(SI);
2000 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2001 Value *Extract = Builder.CreateExtractValue(Val, i, Val->getName());
2002 Builder.CreateStore(Extract, NewElts[i]);
2004 DeadInsts.push_back(SI);
2005 } else if (SIType->isIntegerTy() &&
2006 TD->getTypeAllocSize(SIType) ==
2007 TD->getTypeAllocSize(AI->getAllocatedType())) {
2008 // If this is a store of the entire alloca from an integer, rewrite it.
2009 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
2014 if (isa<SelectInst>(User) || isa<PHINode>(User)) {
2015 // If we have a PHI user of the alloca itself (as opposed to a GEP or
2016 // bitcast) we have to rewrite it. GEP and bitcast uses will be RAUW'd to
2018 if (!isa<AllocaInst>(I)) continue;
2020 assert(Offset == 0 && NewElts[0] &&
2021 "Direct alloca use should have a zero offset");
2023 // If we have a use of the alloca, we know the derived uses will be
2024 // utilizing just the first element of the scalarized result. Insert a
2025 // bitcast of the first alloca before the user as required.
2026 AllocaInst *NewAI = NewElts[0];
2027 BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
2028 NewAI->moveBefore(BCI);
2035 /// RewriteBitCast - Update a bitcast reference to the alloca being replaced
2036 /// and recursively continue updating all of its uses.
2037 void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
2038 SmallVector<AllocaInst*, 32> &NewElts) {
2039 RewriteForScalarRepl(BC, AI, Offset, NewElts);
2040 if (BC->getOperand(0) != AI)
2043 // The bitcast references the original alloca. Replace its uses with
2044 // references to the alloca containing offset zero (which is normally at
2045 // index zero, but might not be in cases involving structs with elements
2047 Type *T = AI->getAllocatedType();
2048 uint64_t EltOffset = 0;
2050 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
2051 Instruction *Val = NewElts[Idx];
2052 if (Val->getType() != BC->getDestTy()) {
2053 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
2056 BC->replaceAllUsesWith(Val);
2057 DeadInsts.push_back(BC);
2060 /// FindElementAndOffset - Return the index of the element containing Offset
2061 /// within the specified type, which must be either a struct or an array.
2062 /// Sets T to the type of the element and Offset to the offset within that
2063 /// element. IdxTy is set to the type of the index result to be used in a
2064 /// GEP instruction.
2065 uint64_t SROA::FindElementAndOffset(Type *&T, uint64_t &Offset,
2068 if (StructType *ST = dyn_cast<StructType>(T)) {
2069 const StructLayout *Layout = TD->getStructLayout(ST);
2070 Idx = Layout->getElementContainingOffset(Offset);
2071 T = ST->getContainedType(Idx);
2072 Offset -= Layout->getElementOffset(Idx);
2073 IdxTy = Type::getInt32Ty(T->getContext());
2075 } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
2076 T = AT->getElementType();
2077 uint64_t EltSize = TD->getTypeAllocSize(T);
2078 Idx = Offset / EltSize;
2079 Offset -= Idx * EltSize;
2080 IdxTy = Type::getInt64Ty(T->getContext());
2083 VectorType *VT = cast<VectorType>(T);
2084 T = VT->getElementType();
2085 uint64_t EltSize = TD->getTypeAllocSize(T);
2086 Idx = Offset / EltSize;
2087 Offset -= Idx * EltSize;
2088 IdxTy = Type::getInt64Ty(T->getContext());
2092 /// RewriteGEP - Check if this GEP instruction moves the pointer across
2093 /// elements of the alloca that are being split apart, and if so, rewrite
2094 /// the GEP to be relative to the new element.
2095 void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
2096 SmallVector<AllocaInst*, 32> &NewElts) {
2097 uint64_t OldOffset = Offset;
2098 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
2099 // If the GEP was dynamic then it must have been a dynamic vector lookup.
2100 // In this case, it must be the last GEP operand which is dynamic so keep that
2101 // aside until we've found the constant GEP offset then add it back in at the
2103 Value* NonConstantIdx = 0;
2104 if (!GEPI->hasAllConstantIndices())
2105 NonConstantIdx = Indices.pop_back_val();
2106 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
2108 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
2110 Type *T = AI->getAllocatedType();
2112 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
2113 if (GEPI->getOperand(0) == AI)
2114 OldIdx = ~0ULL; // Force the GEP to be rewritten.
2116 T = AI->getAllocatedType();
2117 uint64_t EltOffset = Offset;
2118 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
2120 // If this GEP does not move the pointer across elements of the alloca
2121 // being split, then it does not needs to be rewritten.
2125 Type *i32Ty = Type::getInt32Ty(AI->getContext());
2126 SmallVector<Value*, 8> NewArgs;
2127 NewArgs.push_back(Constant::getNullValue(i32Ty));
2128 while (EltOffset != 0) {
2129 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
2130 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
2132 if (NonConstantIdx) {
2134 // This GEP has a dynamic index. We need to add "i32 0" to index through
2135 // any structs or arrays in the original type until we get to the vector
2137 while (!isa<VectorType>(GepTy)) {
2138 NewArgs.push_back(Constant::getNullValue(i32Ty));
2139 GepTy = cast<CompositeType>(GepTy)->getTypeAtIndex(0U);
2141 NewArgs.push_back(NonConstantIdx);
2143 Instruction *Val = NewElts[Idx];
2144 if (NewArgs.size() > 1) {
2145 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs, "", GEPI);
2146 Val->takeName(GEPI);
2148 if (Val->getType() != GEPI->getType())
2149 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
2150 GEPI->replaceAllUsesWith(Val);
2151 DeadInsts.push_back(GEPI);
2154 /// RewriteLifetimeIntrinsic - II is a lifetime.start/lifetime.end. Rewrite it
2155 /// to mark the lifetime of the scalarized memory.
2156 void SROA::RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
2158 SmallVector<AllocaInst*, 32> &NewElts) {
2159 ConstantInt *OldSize = cast<ConstantInt>(II->getArgOperand(0));
2160 // Put matching lifetime markers on everything from Offset up to
2162 Type *AIType = AI->getAllocatedType();
2163 uint64_t NewOffset = Offset;
2165 uint64_t Idx = FindElementAndOffset(AIType, NewOffset, IdxTy);
2167 IRBuilder<> Builder(II);
2168 uint64_t Size = OldSize->getLimitedValue();
2171 // Splice the first element and index 'NewOffset' bytes in. SROA will
2172 // split the alloca again later.
2173 Value *V = Builder.CreateBitCast(NewElts[Idx], Builder.getInt8PtrTy());
2174 V = Builder.CreateGEP(V, Builder.getInt64(NewOffset));
2176 IdxTy = NewElts[Idx]->getAllocatedType();
2177 uint64_t EltSize = TD->getTypeAllocSize(IdxTy) - NewOffset;
2178 if (EltSize > Size) {
2184 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
2185 Builder.CreateLifetimeStart(V, Builder.getInt64(EltSize));
2187 Builder.CreateLifetimeEnd(V, Builder.getInt64(EltSize));
2191 for (; Idx != NewElts.size() && Size; ++Idx) {
2192 IdxTy = NewElts[Idx]->getAllocatedType();
2193 uint64_t EltSize = TD->getTypeAllocSize(IdxTy);
2194 if (EltSize > Size) {
2200 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
2201 Builder.CreateLifetimeStart(NewElts[Idx],
2202 Builder.getInt64(EltSize));
2204 Builder.CreateLifetimeEnd(NewElts[Idx],
2205 Builder.getInt64(EltSize));
2207 DeadInsts.push_back(II);
2210 /// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
2211 /// Rewrite it to copy or set the elements of the scalarized memory.
2212 void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
2214 SmallVector<AllocaInst*, 32> &NewElts) {
2215 // If this is a memcpy/memmove, construct the other pointer as the
2216 // appropriate type. The "Other" pointer is the pointer that goes to memory
2217 // that doesn't have anything to do with the alloca that we are promoting. For
2218 // memset, this Value* stays null.
2219 Value *OtherPtr = 0;
2220 unsigned MemAlignment = MI->getAlignment();
2221 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
2222 if (Inst == MTI->getRawDest())
2223 OtherPtr = MTI->getRawSource();
2225 assert(Inst == MTI->getRawSource());
2226 OtherPtr = MTI->getRawDest();
2230 // If there is an other pointer, we want to convert it to the same pointer
2231 // type as AI has, so we can GEP through it safely.
2233 unsigned AddrSpace =
2234 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
2236 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
2237 // optimization, but it's also required to detect the corner case where
2238 // both pointer operands are referencing the same memory, and where
2239 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
2240 // function is only called for mem intrinsics that access the whole
2241 // aggregate, so non-zero GEPs are not an issue here.)
2242 OtherPtr = OtherPtr->stripPointerCasts();
2244 // Copying the alloca to itself is a no-op: just delete it.
2245 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
2246 // This code will run twice for a no-op memcpy -- once for each operand.
2247 // Put only one reference to MI on the DeadInsts list.
2248 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
2249 E = DeadInsts.end(); I != E; ++I)
2250 if (*I == MI) return;
2251 DeadInsts.push_back(MI);
2255 // If the pointer is not the right type, insert a bitcast to the right
2258 PointerType::get(AI->getType()->getElementType(), AddrSpace);
2260 if (OtherPtr->getType() != NewTy)
2261 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
2264 // Process each element of the aggregate.
2265 bool SROADest = MI->getRawDest() == Inst;
2267 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
2269 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2270 // If this is a memcpy/memmove, emit a GEP of the other element address.
2271 Value *OtherElt = 0;
2272 unsigned OtherEltAlign = MemAlignment;
2275 Value *Idx[2] = { Zero,
2276 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
2277 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx,
2278 OtherPtr->getName()+"."+Twine(i),
2281 PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
2282 Type *OtherTy = OtherPtrTy->getElementType();
2283 if (StructType *ST = dyn_cast<StructType>(OtherTy)) {
2284 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
2286 Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
2287 EltOffset = TD->getTypeAllocSize(EltTy)*i;
2290 // The alignment of the other pointer is the guaranteed alignment of the
2291 // element, which is affected by both the known alignment of the whole
2292 // mem intrinsic and the alignment of the element. If the alignment of
2293 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
2294 // known alignment is just 4 bytes.
2295 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
2298 Value *EltPtr = NewElts[i];
2299 Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
2301 // If we got down to a scalar, insert a load or store as appropriate.
2302 if (EltTy->isSingleValueType()) {
2303 if (isa<MemTransferInst>(MI)) {
2305 // From Other to Alloca.
2306 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
2307 new StoreInst(Elt, EltPtr, MI);
2309 // From Alloca to Other.
2310 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
2311 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
2315 assert(isa<MemSetInst>(MI));
2317 // If the stored element is zero (common case), just store a null
2320 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
2322 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
2324 // If EltTy is a vector type, get the element type.
2325 Type *ValTy = EltTy->getScalarType();
2327 // Construct an integer with the right value.
2328 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
2329 APInt OneVal(EltSize, CI->getZExtValue());
2330 APInt TotalVal(OneVal);
2332 for (unsigned i = 0; 8*i < EltSize; ++i) {
2333 TotalVal = TotalVal.shl(8);
2337 // Convert the integer value to the appropriate type.
2338 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
2339 if (ValTy->isPointerTy())
2340 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
2341 else if (ValTy->isFloatingPointTy())
2342 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
2343 assert(StoreVal->getType() == ValTy && "Type mismatch!");
2345 // If the requested value was a vector constant, create it.
2346 if (EltTy->isVectorTy()) {
2347 unsigned NumElts = cast<VectorType>(EltTy)->getNumElements();
2348 StoreVal = ConstantVector::getSplat(NumElts, StoreVal);
2351 new StoreInst(StoreVal, EltPtr, MI);
2354 // Otherwise, if we're storing a byte variable, use a memset call for
2358 unsigned EltSize = TD->getTypeAllocSize(EltTy);
2362 IRBuilder<> Builder(MI);
2364 // Finally, insert the meminst for this element.
2365 if (isa<MemSetInst>(MI)) {
2366 Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
2369 assert(isa<MemTransferInst>(MI));
2370 Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr
2371 Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr
2373 if (isa<MemCpyInst>(MI))
2374 Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
2376 Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
2379 DeadInsts.push_back(MI);
2382 /// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
2383 /// overwrites the entire allocation. Extract out the pieces of the stored
2384 /// integer and store them individually.
2385 void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
2386 SmallVector<AllocaInst*, 32> &NewElts){
2387 // Extract each element out of the integer according to its structure offset
2388 // and store the element value to the individual alloca.
2389 Value *SrcVal = SI->getOperand(0);
2390 Type *AllocaEltTy = AI->getAllocatedType();
2391 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
2393 IRBuilder<> Builder(SI);
2395 // Handle tail padding by extending the operand
2396 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
2397 SrcVal = Builder.CreateZExt(SrcVal,
2398 IntegerType::get(SI->getContext(), AllocaSizeBits));
2400 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
2403 // There are two forms here: AI could be an array or struct. Both cases
2404 // have different ways to compute the element offset.
2405 if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2406 const StructLayout *Layout = TD->getStructLayout(EltSTy);
2408 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2409 // Get the number of bits to shift SrcVal to get the value.
2410 Type *FieldTy = EltSTy->getElementType(i);
2411 uint64_t Shift = Layout->getElementOffsetInBits(i);
2413 if (TD->isBigEndian())
2414 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
2416 Value *EltVal = SrcVal;
2418 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
2419 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
2422 // Truncate down to an integer of the right size.
2423 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
2425 // Ignore zero sized fields like {}, they obviously contain no data.
2426 if (FieldSizeBits == 0) continue;
2428 if (FieldSizeBits != AllocaSizeBits)
2429 EltVal = Builder.CreateTrunc(EltVal,
2430 IntegerType::get(SI->getContext(), FieldSizeBits));
2431 Value *DestField = NewElts[i];
2432 if (EltVal->getType() == FieldTy) {
2433 // Storing to an integer field of this size, just do it.
2434 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
2435 // Bitcast to the right element type (for fp/vector values).
2436 EltVal = Builder.CreateBitCast(EltVal, FieldTy);
2438 // Otherwise, bitcast the dest pointer (for aggregates).
2439 DestField = Builder.CreateBitCast(DestField,
2440 PointerType::getUnqual(EltVal->getType()));
2442 new StoreInst(EltVal, DestField, SI);
2446 ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
2447 Type *ArrayEltTy = ATy->getElementType();
2448 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
2449 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
2453 if (TD->isBigEndian())
2454 Shift = AllocaSizeBits-ElementOffset;
2458 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2459 // Ignore zero sized fields like {}, they obviously contain no data.
2460 if (ElementSizeBits == 0) continue;
2462 Value *EltVal = SrcVal;
2464 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
2465 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
2468 // Truncate down to an integer of the right size.
2469 if (ElementSizeBits != AllocaSizeBits)
2470 EltVal = Builder.CreateTrunc(EltVal,
2471 IntegerType::get(SI->getContext(),
2473 Value *DestField = NewElts[i];
2474 if (EltVal->getType() == ArrayEltTy) {
2475 // Storing to an integer field of this size, just do it.
2476 } else if (ArrayEltTy->isFloatingPointTy() ||
2477 ArrayEltTy->isVectorTy()) {
2478 // Bitcast to the right element type (for fp/vector values).
2479 EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
2481 // Otherwise, bitcast the dest pointer (for aggregates).
2482 DestField = Builder.CreateBitCast(DestField,
2483 PointerType::getUnqual(EltVal->getType()));
2485 new StoreInst(EltVal, DestField, SI);
2487 if (TD->isBigEndian())
2488 Shift -= ElementOffset;
2490 Shift += ElementOffset;
2494 DeadInsts.push_back(SI);
2497 /// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
2498 /// an integer. Load the individual pieces to form the aggregate value.
2499 void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
2500 SmallVector<AllocaInst*, 32> &NewElts) {
2501 // Extract each element out of the NewElts according to its structure offset
2502 // and form the result value.
2503 Type *AllocaEltTy = AI->getAllocatedType();
2504 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
2506 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
2509 // There are two forms here: AI could be an array or struct. Both cases
2510 // have different ways to compute the element offset.
2511 const StructLayout *Layout = 0;
2512 uint64_t ArrayEltBitOffset = 0;
2513 if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2514 Layout = TD->getStructLayout(EltSTy);
2516 Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
2517 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
2521 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
2523 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2524 // Load the value from the alloca. If the NewElt is an aggregate, cast
2525 // the pointer to an integer of the same size before doing the load.
2526 Value *SrcField = NewElts[i];
2528 cast<PointerType>(SrcField->getType())->getElementType();
2529 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
2531 // Ignore zero sized fields like {}, they obviously contain no data.
2532 if (FieldSizeBits == 0) continue;
2534 IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
2536 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
2537 !FieldTy->isVectorTy())
2538 SrcField = new BitCastInst(SrcField,
2539 PointerType::getUnqual(FieldIntTy),
2541 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
2543 // If SrcField is a fp or vector of the right size but that isn't an
2544 // integer type, bitcast to an integer so we can shift it.
2545 if (SrcField->getType() != FieldIntTy)
2546 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
2548 // Zero extend the field to be the same size as the final alloca so that
2549 // we can shift and insert it.
2550 if (SrcField->getType() != ResultVal->getType())
2551 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
2553 // Determine the number of bits to shift SrcField.
2555 if (Layout) // Struct case.
2556 Shift = Layout->getElementOffsetInBits(i);
2558 Shift = i*ArrayEltBitOffset;
2560 if (TD->isBigEndian())
2561 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
2564 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
2565 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
2568 // Don't create an 'or x, 0' on the first iteration.
2569 if (!isa<Constant>(ResultVal) ||
2570 !cast<Constant>(ResultVal)->isNullValue())
2571 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
2573 ResultVal = SrcField;
2576 // Handle tail padding by truncating the result
2577 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
2578 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
2580 LI->replaceAllUsesWith(ResultVal);
2581 DeadInsts.push_back(LI);
2584 /// HasPadding - Return true if the specified type has any structure or
2585 /// alignment padding in between the elements that would be split apart
2586 /// by SROA; return false otherwise.
2587 static bool HasPadding(Type *Ty, const TargetData &TD) {
2588 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2589 Ty = ATy->getElementType();
2590 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
2593 // SROA currently handles only Arrays and Structs.
2594 StructType *STy = cast<StructType>(Ty);
2595 const StructLayout *SL = TD.getStructLayout(STy);
2596 unsigned PrevFieldBitOffset = 0;
2597 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2598 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
2600 // Check to see if there is any padding between this element and the
2603 unsigned PrevFieldEnd =
2604 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
2605 if (PrevFieldEnd < FieldBitOffset)
2608 PrevFieldBitOffset = FieldBitOffset;
2610 // Check for tail padding.
2611 if (unsigned EltCount = STy->getNumElements()) {
2612 unsigned PrevFieldEnd = PrevFieldBitOffset +
2613 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
2614 if (PrevFieldEnd < SL->getSizeInBits())
2620 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
2621 /// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
2622 /// or 1 if safe after canonicalization has been performed.
2623 bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
2624 // Loop over the use list of the alloca. We can only transform it if all of
2625 // the users are safe to transform.
2626 AllocaInfo Info(AI);
2628 isSafeForScalarRepl(AI, 0, Info);
2629 if (Info.isUnsafe) {
2630 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
2634 // Okay, we know all the users are promotable. If the aggregate is a memcpy
2635 // source and destination, we have to be careful. In particular, the memcpy
2636 // could be moving around elements that live in structure padding of the LLVM
2637 // types, but may actually be used. In these cases, we refuse to promote the
2639 if (Info.isMemCpySrc && Info.isMemCpyDst &&
2640 HasPadding(AI->getAllocatedType(), *TD))
2643 // If the alloca never has an access to just *part* of it, but is accessed
2644 // via loads and stores, then we should use ConvertToScalarInfo to promote
2645 // the alloca instead of promoting each piece at a time and inserting fission
2647 if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
2648 // If the struct/array just has one element, use basic SRoA.
2649 if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
2650 if (ST->getNumElements() > 1) return false;
2652 if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
2662 /// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
2663 /// some part of a constant global variable. This intentionally only accepts
2664 /// constant expressions because we don't can't rewrite arbitrary instructions.
2665 static bool PointsToConstantGlobal(Value *V) {
2666 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
2667 return GV->isConstant();
2668 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2669 if (CE->getOpcode() == Instruction::BitCast ||
2670 CE->getOpcode() == Instruction::GetElementPtr)
2671 return PointsToConstantGlobal(CE->getOperand(0));
2675 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
2676 /// pointer to an alloca. Ignore any reads of the pointer, return false if we
2677 /// see any stores or other unknown uses. If we see pointer arithmetic, keep
2678 /// track of whether it moves the pointer (with isOffset) but otherwise traverse
2679 /// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
2680 /// the alloca, and if the source pointer is a pointer to a constant global, we
2681 /// can optimize this.
2683 isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
2685 SmallVector<Instruction *, 4> &LifetimeMarkers) {
2686 // We track lifetime intrinsics as we encounter them. If we decide to go
2687 // ahead and replace the value with the global, this lets the caller quickly
2688 // eliminate the markers.
2690 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
2691 User *U = cast<Instruction>(*UI);
2693 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
2694 // Ignore non-volatile loads, they are always ok.
2695 if (!LI->isSimple()) return false;
2699 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
2700 // If uses of the bitcast are ok, we are ok.
2701 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset,
2706 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
2707 // If the GEP has all zero indices, it doesn't offset the pointer. If it
2708 // doesn't, it does.
2709 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
2710 isOffset || !GEP->hasAllZeroIndices(),
2716 if (CallSite CS = U) {
2717 // If this is the function being called then we treat it like a load and
2719 if (CS.isCallee(UI))
2722 // If this is a readonly/readnone call site, then we know it is just a
2723 // load (but one that potentially returns the value itself), so we can
2724 // ignore it if we know that the value isn't captured.
2725 unsigned ArgNo = CS.getArgumentNo(UI);
2726 if (CS.onlyReadsMemory() &&
2727 (CS.getInstruction()->use_empty() || CS.doesNotCapture(ArgNo)))
2730 // If this is being passed as a byval argument, the caller is making a
2731 // copy, so it is only a read of the alloca.
2732 if (CS.isByValArgument(ArgNo))
2736 // Lifetime intrinsics can be handled by the caller.
2737 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
2738 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2739 II->getIntrinsicID() == Intrinsic::lifetime_end) {
2740 assert(II->use_empty() && "Lifetime markers have no result to use!");
2741 LifetimeMarkers.push_back(II);
2746 // If this is isn't our memcpy/memmove, reject it as something we can't
2748 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
2752 // If the transfer is using the alloca as a source of the transfer, then
2753 // ignore it since it is a load (unless the transfer is volatile).
2754 if (UI.getOperandNo() == 1) {
2755 if (MI->isVolatile()) return false;
2759 // If we already have seen a copy, reject the second one.
2760 if (TheCopy) return false;
2762 // If the pointer has been offset from the start of the alloca, we can't
2763 // safely handle this.
2764 if (isOffset) return false;
2766 // If the memintrinsic isn't using the alloca as the dest, reject it.
2767 if (UI.getOperandNo() != 0) return false;
2769 // If the source of the memcpy/move is not a constant global, reject it.
2770 if (!PointsToConstantGlobal(MI->getSource()))
2773 // Otherwise, the transform is safe. Remember the copy instruction.
2779 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
2780 /// modified by a copy from a constant global. If we can prove this, we can
2781 /// replace any uses of the alloca with uses of the global directly.
2783 SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
2784 SmallVector<Instruction*, 4> &ToDelete) {
2785 MemTransferInst *TheCopy = 0;
2786 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false, ToDelete))