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/ADT/SetVector.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Analysis/Loads.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/IR/CallSite.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/DIBuilder.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/DebugInfo.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/Dominators.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/GetElementPtrTypeIterator.h"
38 #include "llvm/IR/GlobalVariable.h"
39 #include "llvm/IR/IRBuilder.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/IntrinsicInst.h"
42 #include "llvm/IR/LLVMContext.h"
43 #include "llvm/IR/Module.h"
44 #include "llvm/IR/Operator.h"
45 #include "llvm/Pass.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Support/raw_ostream.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");
61 struct SROA : public FunctionPass {
62 SROA(int T, bool hasDT, char &ID, int ST, int AT, int SLT)
63 : FunctionPass(ID), HasDomTree(hasDT) {
69 StructMemberThreshold = 32;
71 StructMemberThreshold = ST;
73 ArrayElementThreshold = 8;
75 ArrayElementThreshold = AT;
77 // Do not limit the scalar integer load size if no threshold is given.
78 ScalarLoadThreshold = -1;
80 ScalarLoadThreshold = SLT;
83 bool runOnFunction(Function &F) override;
85 bool performScalarRepl(Function &F);
86 bool performPromotion(Function &F);
92 /// DeadInsts - Keep track of instructions we have made dead, so that
93 /// we can remove them after we are done working.
94 SmallVector<Value*, 32> DeadInsts;
96 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
97 /// information about the uses. All these fields are initialized to false
98 /// and set to true when something is learned.
100 /// The alloca to promote.
103 /// CheckedPHIs - This is a set of verified PHI nodes, to prevent infinite
104 /// looping and avoid redundant work.
105 SmallPtrSet<PHINode*, 8> CheckedPHIs;
107 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
110 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
111 bool isMemCpySrc : 1;
113 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
114 bool isMemCpyDst : 1;
116 /// hasSubelementAccess - This is true if a subelement of the alloca is
117 /// ever accessed, or false if the alloca is only accessed with mem
118 /// intrinsics or load/store that only access the entire alloca at once.
119 bool hasSubelementAccess : 1;
121 /// hasALoadOrStore - This is true if there are any loads or stores to it.
122 /// The alloca may just be accessed with memcpy, for example, which would
124 bool hasALoadOrStore : 1;
126 explicit AllocaInfo(AllocaInst *ai)
127 : AI(ai), isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
128 hasSubelementAccess(false), hasALoadOrStore(false) {}
131 /// SRThreshold - The maximum alloca size to considered for SROA.
132 unsigned SRThreshold;
134 /// StructMemberThreshold - The maximum number of members a struct can
135 /// contain to be considered for SROA.
136 unsigned StructMemberThreshold;
138 /// ArrayElementThreshold - The maximum number of elements an array can
139 /// have to be considered for SROA.
140 unsigned ArrayElementThreshold;
142 /// ScalarLoadThreshold - The maximum size in bits of scalars to load when
143 /// converting to scalar
144 unsigned ScalarLoadThreshold;
146 void MarkUnsafe(AllocaInfo &I, Instruction *User) {
148 DEBUG(dbgs() << " Transformation preventing inst: " << *User << '\n');
151 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
153 void isSafeForScalarRepl(Instruction *I, uint64_t Offset, AllocaInfo &Info);
154 void isSafePHISelectUseForScalarRepl(Instruction *User, uint64_t Offset,
156 void isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset, AllocaInfo &Info);
157 void isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
158 Type *MemOpType, bool isStore, AllocaInfo &Info,
159 Instruction *TheAccess, bool AllowWholeAccess);
160 bool TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size);
161 uint64_t FindElementAndOffset(Type *&T, uint64_t &Offset,
164 void DoScalarReplacement(AllocaInst *AI,
165 std::vector<AllocaInst*> &WorkList);
166 void DeleteDeadInstructions();
168 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
169 SmallVectorImpl<AllocaInst *> &NewElts);
170 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
171 SmallVectorImpl<AllocaInst *> &NewElts);
172 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
173 SmallVectorImpl<AllocaInst *> &NewElts);
174 void RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
176 SmallVectorImpl<AllocaInst *> &NewElts);
177 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
179 SmallVectorImpl<AllocaInst *> &NewElts);
180 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
181 SmallVectorImpl<AllocaInst *> &NewElts);
182 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
183 SmallVectorImpl<AllocaInst *> &NewElts);
184 bool ShouldAttemptScalarRepl(AllocaInst *AI);
187 // SROA_DT - SROA that uses DominatorTree.
188 struct SROA_DT : public SROA {
191 SROA_DT(int T = -1, int ST = -1, int AT = -1, int SLT = -1) :
192 SROA(T, true, ID, ST, AT, SLT) {
193 initializeSROA_DTPass(*PassRegistry::getPassRegistry());
196 // getAnalysisUsage - This pass does not require any passes, but we know it
197 // will not alter the CFG, so say so.
198 void getAnalysisUsage(AnalysisUsage &AU) const override {
199 AU.addRequired<DominatorTreeWrapperPass>();
200 AU.setPreservesCFG();
204 // SROA_SSAUp - SROA that uses SSAUpdater.
205 struct SROA_SSAUp : public SROA {
208 SROA_SSAUp(int T = -1, int ST = -1, int AT = -1, int SLT = -1) :
209 SROA(T, false, ID, ST, AT, SLT) {
210 initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
213 // getAnalysisUsage - This pass does not require any passes, but we know it
214 // will not alter the CFG, so say so.
215 void getAnalysisUsage(AnalysisUsage &AU) const override {
216 AU.setPreservesCFG();
222 char SROA_DT::ID = 0;
223 char SROA_SSAUp::ID = 0;
225 INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl",
226 "Scalar Replacement of Aggregates (DT)", false, false)
227 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
228 INITIALIZE_PASS_END(SROA_DT, "scalarrepl",
229 "Scalar Replacement of Aggregates (DT)", false, false)
231 INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
232 "Scalar Replacement of Aggregates (SSAUp)", false, false)
233 INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
234 "Scalar Replacement of Aggregates (SSAUp)", false, false)
236 // Public interface to the ScalarReplAggregates pass
237 FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
239 int StructMemberThreshold,
240 int ArrayElementThreshold,
241 int ScalarLoadThreshold) {
243 return new SROA_DT(Threshold, StructMemberThreshold, ArrayElementThreshold,
244 ScalarLoadThreshold);
245 return new SROA_SSAUp(Threshold, StructMemberThreshold,
246 ArrayElementThreshold, ScalarLoadThreshold);
250 //===----------------------------------------------------------------------===//
251 // Convert To Scalar Optimization.
252 //===----------------------------------------------------------------------===//
255 /// ConvertToScalarInfo - This class implements the "Convert To Scalar"
256 /// optimization, which scans the uses of an alloca and determines if it can
257 /// rewrite it in terms of a single new alloca that can be mem2reg'd.
258 class ConvertToScalarInfo {
259 /// AllocaSize - The size of the alloca being considered in bytes.
261 const DataLayout &DL;
262 unsigned ScalarLoadThreshold;
264 /// IsNotTrivial - This is set to true if there is some access to the object
265 /// which means that mem2reg can't promote it.
268 /// ScalarKind - Tracks the kind of alloca being considered for promotion,
269 /// computed based on the uses of the alloca rather than the LLVM type system.
273 // Accesses via GEPs that are consistent with element access of a vector
274 // type. This will not be converted into a vector unless there is a later
275 // access using an actual vector type.
278 // Accesses via vector operations and GEPs that are consistent with the
279 // layout of a vector type.
282 // An integer bag-of-bits with bitwise operations for insertion and
283 // extraction. Any combination of types can be converted into this kind
288 /// VectorTy - This tracks the type that we should promote the vector to if
289 /// it is possible to turn it into a vector. This starts out null, and if it
290 /// isn't possible to turn into a vector type, it gets set to VoidTy.
291 VectorType *VectorTy;
293 /// HadNonMemTransferAccess - True if there is at least one access to the
294 /// alloca that is not a MemTransferInst. We don't want to turn structs into
295 /// large integers unless there is some potential for optimization.
296 bool HadNonMemTransferAccess;
298 /// HadDynamicAccess - True if some element of this alloca was dynamic.
299 /// We don't yet have support for turning a dynamic access into a large
301 bool HadDynamicAccess;
304 explicit ConvertToScalarInfo(unsigned Size, const DataLayout &DL,
306 : AllocaSize(Size), DL(DL), ScalarLoadThreshold(SLT), IsNotTrivial(false),
307 ScalarKind(Unknown), VectorTy(0), HadNonMemTransferAccess(false),
308 HadDynamicAccess(false) { }
310 AllocaInst *TryConvert(AllocaInst *AI);
313 bool CanConvertToScalar(Value *V, uint64_t Offset, Value* NonConstantIdx);
314 void MergeInTypeForLoadOrStore(Type *In, uint64_t Offset);
315 bool MergeInVectorType(VectorType *VInTy, uint64_t Offset);
316 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset,
317 Value *NonConstantIdx);
319 Value *ConvertScalar_ExtractValue(Value *NV, Type *ToType,
320 uint64_t Offset, Value* NonConstantIdx,
321 IRBuilder<> &Builder);
322 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
323 uint64_t Offset, Value* NonConstantIdx,
324 IRBuilder<> &Builder);
326 } // end anonymous namespace.
329 /// TryConvert - Analyze the specified alloca, and if it is safe to do so,
330 /// rewrite it to be a new alloca which is mem2reg'able. This returns the new
331 /// alloca if possible or null if not.
332 AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
333 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
335 if (!CanConvertToScalar(AI, 0, 0) || !IsNotTrivial)
338 // If an alloca has only memset / memcpy uses, it may still have an Unknown
339 // ScalarKind. Treat it as an Integer below.
340 if (ScalarKind == Unknown)
341 ScalarKind = Integer;
343 if (ScalarKind == Vector && VectorTy->getBitWidth() != AllocaSize * 8)
344 ScalarKind = Integer;
346 // If we were able to find a vector type that can handle this with
347 // insert/extract elements, and if there was at least one use that had
348 // a vector type, promote this to a vector. We don't want to promote
349 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
350 // we just get a lot of insert/extracts. If at least one vector is
351 // involved, then we probably really do have a union of vector/array.
353 if (ScalarKind == Vector) {
354 assert(VectorTy && "Missing type for vector scalar.");
355 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
356 << *VectorTy << '\n');
357 NewTy = VectorTy; // Use the vector type.
359 unsigned BitWidth = AllocaSize * 8;
361 // Do not convert to scalar integer if the alloca size exceeds the
362 // scalar load threshold.
363 if (BitWidth > ScalarLoadThreshold)
366 if ((ScalarKind == ImplicitVector || ScalarKind == Integer) &&
367 !HadNonMemTransferAccess && !DL.fitsInLegalInteger(BitWidth))
369 // Dynamic accesses on integers aren't yet supported. They need us to shift
370 // by a dynamic amount which could be difficult to work out as we might not
371 // know whether to use a left or right shift.
372 if (ScalarKind == Integer && HadDynamicAccess)
375 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
376 // Create and insert the integer alloca.
377 NewTy = IntegerType::get(AI->getContext(), BitWidth);
379 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
380 ConvertUsesToScalar(AI, NewAI, 0, 0);
384 /// MergeInTypeForLoadOrStore - Add the 'In' type to the accumulated vector type
385 /// (VectorTy) so far at the offset specified by Offset (which is specified in
388 /// There are two cases we handle here:
389 /// 1) A union of vector types of the same size and potentially its elements.
390 /// Here we turn element accesses into insert/extract element operations.
391 /// This promotes a <4 x float> with a store of float to the third element
392 /// into a <4 x float> that uses insert element.
393 /// 2) A fully general blob of memory, which we turn into some (potentially
394 /// large) integer type with extract and insert operations where the loads
395 /// and stores would mutate the memory. We mark this by setting VectorTy
397 void ConvertToScalarInfo::MergeInTypeForLoadOrStore(Type *In,
399 // If we already decided to turn this into a blob of integer memory, there is
400 // nothing to be done.
401 if (ScalarKind == Integer)
404 // If this could be contributing to a vector, analyze it.
406 // If the In type is a vector that is the same size as the alloca, see if it
407 // matches the existing VecTy.
408 if (VectorType *VInTy = dyn_cast<VectorType>(In)) {
409 if (MergeInVectorType(VInTy, Offset))
411 } else if (In->isFloatTy() || In->isDoubleTy() ||
412 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
413 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
414 // Full width accesses can be ignored, because they can always be turned
416 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
417 if (EltSize == AllocaSize)
420 // If we're accessing something that could be an element of a vector, see
421 // if the implied vector agrees with what we already have and if Offset is
422 // compatible with it.
423 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
424 (!VectorTy || EltSize == VectorTy->getElementType()
425 ->getPrimitiveSizeInBits()/8)) {
427 ScalarKind = ImplicitVector;
428 VectorTy = VectorType::get(In, AllocaSize/EltSize);
434 // Otherwise, we have a case that we can't handle with an optimized vector
435 // form. We can still turn this into a large integer.
436 ScalarKind = Integer;
439 /// MergeInVectorType - Handles the vector case of MergeInTypeForLoadOrStore,
440 /// returning true if the type was successfully merged and false otherwise.
441 bool ConvertToScalarInfo::MergeInVectorType(VectorType *VInTy,
443 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
444 // If we're storing/loading a vector of the right size, allow it as a
445 // vector. If this the first vector we see, remember the type so that
446 // we know the element size. If this is a subsequent access, ignore it
447 // even if it is a differing type but the same size. Worst case we can
448 // bitcast the resultant vectors.
458 /// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
459 /// its accesses to a single vector type, return true and set VecTy to
460 /// the new type. If we could convert the alloca into a single promotable
461 /// integer, return true but set VecTy to VoidTy. Further, if the use is not a
462 /// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
463 /// is the current offset from the base of the alloca being analyzed.
465 /// If we see at least one access to the value that is as a vector type, set the
467 bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset,
468 Value* NonConstantIdx) {
469 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
470 Instruction *User = cast<Instruction>(*UI);
472 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
473 // Don't break volatile loads.
476 // Don't touch MMX operations.
477 if (LI->getType()->isX86_MMXTy())
479 HadNonMemTransferAccess = true;
480 MergeInTypeForLoadOrStore(LI->getType(), Offset);
484 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
485 // Storing the pointer, not into the value?
486 if (SI->getOperand(0) == V || !SI->isSimple()) return false;
487 // Don't touch MMX operations.
488 if (SI->getOperand(0)->getType()->isX86_MMXTy())
490 HadNonMemTransferAccess = true;
491 MergeInTypeForLoadOrStore(SI->getOperand(0)->getType(), Offset);
495 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
496 if (!onlyUsedByLifetimeMarkers(BCI))
497 IsNotTrivial = true; // Can't be mem2reg'd.
498 if (!CanConvertToScalar(BCI, Offset, NonConstantIdx))
503 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
504 // If this is a GEP with a variable indices, we can't handle it.
505 PointerType* PtrTy = dyn_cast<PointerType>(GEP->getPointerOperandType());
509 // Compute the offset that this GEP adds to the pointer.
510 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
511 Value *GEPNonConstantIdx = 0;
512 if (!GEP->hasAllConstantIndices()) {
513 if (!isa<VectorType>(PtrTy->getElementType()))
517 GEPNonConstantIdx = Indices.pop_back_val();
518 if (!GEPNonConstantIdx->getType()->isIntegerTy(32))
520 HadDynamicAccess = true;
522 GEPNonConstantIdx = NonConstantIdx;
523 uint64_t GEPOffset = DL.getIndexedOffset(PtrTy,
525 // See if all uses can be converted.
526 if (!CanConvertToScalar(GEP, Offset+GEPOffset, GEPNonConstantIdx))
528 IsNotTrivial = true; // Can't be mem2reg'd.
529 HadNonMemTransferAccess = true;
533 // If this is a constant sized memset of a constant value (e.g. 0) we can
535 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
536 // Store to dynamic index.
539 // Store of constant value.
540 if (!isa<ConstantInt>(MSI->getValue()))
543 // Store of constant size.
544 ConstantInt *Len = dyn_cast<ConstantInt>(MSI->getLength());
548 // If the size differs from the alloca, we can only convert the alloca to
549 // an integer bag-of-bits.
550 // FIXME: This should handle all of the cases that are currently accepted
551 // as vector element insertions.
552 if (Len->getZExtValue() != AllocaSize || Offset != 0)
553 ScalarKind = Integer;
555 IsNotTrivial = true; // Can't be mem2reg'd.
556 HadNonMemTransferAccess = true;
560 // If this is a memcpy or memmove into or out of the whole allocation, we
561 // can handle it like a load or store of the scalar type.
562 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
563 // Store to dynamic index.
566 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
567 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
570 IsNotTrivial = true; // Can't be mem2reg'd.
574 // If this is a lifetime intrinsic, we can handle it.
575 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
576 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
577 II->getIntrinsicID() == Intrinsic::lifetime_end) {
582 // Otherwise, we cannot handle this!
589 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
590 /// directly. This happens when we are converting an "integer union" to a
591 /// single integer scalar, or when we are converting a "vector union" to a
592 /// vector with insert/extractelement instructions.
594 /// Offset is an offset from the original alloca, in bits that need to be
595 /// shifted to the right. By the end of this, there should be no uses of Ptr.
596 void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
598 Value* NonConstantIdx) {
599 while (!Ptr->use_empty()) {
600 Instruction *User = cast<Instruction>(Ptr->use_back());
602 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
603 ConvertUsesToScalar(CI, NewAI, Offset, NonConstantIdx);
604 CI->eraseFromParent();
608 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
609 // Compute the offset that this GEP adds to the pointer.
610 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
611 Value* GEPNonConstantIdx = 0;
612 if (!GEP->hasAllConstantIndices()) {
613 assert(!NonConstantIdx &&
614 "Dynamic GEP reading from dynamic GEP unsupported");
615 GEPNonConstantIdx = Indices.pop_back_val();
617 GEPNonConstantIdx = NonConstantIdx;
618 uint64_t GEPOffset = DL.getIndexedOffset(GEP->getPointerOperandType(),
620 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8, GEPNonConstantIdx);
621 GEP->eraseFromParent();
625 IRBuilder<> Builder(User);
627 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
628 // The load is a bit extract from NewAI shifted right by Offset bits.
629 Value *LoadedVal = Builder.CreateLoad(NewAI);
631 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset,
632 NonConstantIdx, Builder);
633 LI->replaceAllUsesWith(NewLoadVal);
634 LI->eraseFromParent();
638 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
639 assert(SI->getOperand(0) != Ptr && "Consistency error!");
640 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
641 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
642 NonConstantIdx, Builder);
643 Builder.CreateStore(New, NewAI);
644 SI->eraseFromParent();
646 // If the load we just inserted is now dead, then the inserted store
647 // overwrote the entire thing.
648 if (Old->use_empty())
649 Old->eraseFromParent();
653 // If this is a constant sized memset of a constant value (e.g. 0) we can
654 // transform it into a store of the expanded constant value.
655 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
656 assert(MSI->getRawDest() == Ptr && "Consistency error!");
657 assert(!NonConstantIdx && "Cannot replace dynamic memset with insert");
658 int64_t SNumBytes = cast<ConstantInt>(MSI->getLength())->getSExtValue();
659 if (SNumBytes > 0 && (SNumBytes >> 32) == 0) {
660 unsigned NumBytes = static_cast<unsigned>(SNumBytes);
661 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
663 // Compute the value replicated the right number of times.
664 APInt APVal(NumBytes*8, Val);
666 // Splat the value if non-zero.
668 for (unsigned i = 1; i != NumBytes; ++i)
671 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
672 Value *New = ConvertScalar_InsertValue(
673 ConstantInt::get(User->getContext(), APVal),
674 Old, Offset, 0, Builder);
675 Builder.CreateStore(New, NewAI);
677 // If the load we just inserted is now dead, then the memset overwrote
679 if (Old->use_empty())
680 Old->eraseFromParent();
682 MSI->eraseFromParent();
686 // If this is a memcpy or memmove into or out of the whole allocation, we
687 // can handle it like a load or store of the scalar type.
688 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
689 assert(Offset == 0 && "must be store to start of alloca");
690 assert(!NonConstantIdx && "Cannot replace dynamic transfer with insert");
692 // If the source and destination are both to the same alloca, then this is
693 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
695 AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, &DL, 0));
697 if (GetUnderlyingObject(MTI->getSource(), &DL, 0) != OrigAI) {
698 // Dest must be OrigAI, change this to be a load from the original
699 // pointer (bitcasted), then a store to our new alloca.
700 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
701 Value *SrcPtr = MTI->getSource();
702 PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
703 PointerType* AIPTy = cast<PointerType>(NewAI->getType());
704 if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
705 AIPTy = PointerType::get(AIPTy->getElementType(),
706 SPTy->getAddressSpace());
708 SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
710 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
711 SrcVal->setAlignment(MTI->getAlignment());
712 Builder.CreateStore(SrcVal, NewAI);
713 } else if (GetUnderlyingObject(MTI->getDest(), &DL, 0) != OrigAI) {
714 // Src must be OrigAI, change this to be a load from NewAI then a store
715 // through the original dest pointer (bitcasted).
716 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
717 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
719 PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
720 PointerType* AIPTy = cast<PointerType>(NewAI->getType());
721 if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
722 AIPTy = PointerType::get(AIPTy->getElementType(),
723 DPTy->getAddressSpace());
725 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
727 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
728 NewStore->setAlignment(MTI->getAlignment());
730 // Noop transfer. Src == Dst
733 MTI->eraseFromParent();
737 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
738 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
739 II->getIntrinsicID() == Intrinsic::lifetime_end) {
740 // There's no need to preserve these, as the resulting alloca will be
741 // converted to a register anyways.
742 II->eraseFromParent();
747 llvm_unreachable("Unsupported operation!");
751 /// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
752 /// or vector value FromVal, extracting the bits from the offset specified by
753 /// Offset. This returns the value, which is of type ToType.
755 /// This happens when we are converting an "integer union" to a single
756 /// integer scalar, or when we are converting a "vector union" to a vector with
757 /// insert/extractelement instructions.
759 /// Offset is an offset from the original alloca, in bits that need to be
760 /// shifted to the right.
761 Value *ConvertToScalarInfo::
762 ConvertScalar_ExtractValue(Value *FromVal, Type *ToType,
763 uint64_t Offset, Value* NonConstantIdx,
764 IRBuilder<> &Builder) {
765 // If the load is of the whole new alloca, no conversion is needed.
766 Type *FromType = FromVal->getType();
767 if (FromType == ToType && Offset == 0)
770 // If the result alloca is a vector type, this is either an element
771 // access or a bitcast to another vector type of the same size.
772 if (VectorType *VTy = dyn_cast<VectorType>(FromType)) {
773 unsigned FromTypeSize = DL.getTypeAllocSize(FromType);
774 unsigned ToTypeSize = DL.getTypeAllocSize(ToType);
775 if (FromTypeSize == ToTypeSize)
776 return Builder.CreateBitCast(FromVal, ToType);
778 // Otherwise it must be an element access.
781 unsigned EltSize = DL.getTypeAllocSizeInBits(VTy->getElementType());
782 Elt = Offset/EltSize;
783 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
785 // Return the element extracted out of it.
787 if (NonConstantIdx) {
789 Idx = Builder.CreateAdd(NonConstantIdx,
790 Builder.getInt32(Elt),
793 Idx = NonConstantIdx;
795 Idx = Builder.getInt32(Elt);
796 Value *V = Builder.CreateExtractElement(FromVal, Idx);
797 if (V->getType() != ToType)
798 V = Builder.CreateBitCast(V, ToType);
802 // If ToType is a first class aggregate, extract out each of the pieces and
803 // use insertvalue's to form the FCA.
804 if (StructType *ST = dyn_cast<StructType>(ToType)) {
805 assert(!NonConstantIdx &&
806 "Dynamic indexing into struct types not supported");
807 const StructLayout &Layout = *DL.getStructLayout(ST);
808 Value *Res = UndefValue::get(ST);
809 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
810 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
811 Offset+Layout.getElementOffsetInBits(i),
813 Res = Builder.CreateInsertValue(Res, Elt, i);
818 if (ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
819 assert(!NonConstantIdx &&
820 "Dynamic indexing into array types not supported");
821 uint64_t EltSize = DL.getTypeAllocSizeInBits(AT->getElementType());
822 Value *Res = UndefValue::get(AT);
823 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
824 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
825 Offset+i*EltSize, 0, Builder);
826 Res = Builder.CreateInsertValue(Res, Elt, i);
831 // Otherwise, this must be a union that was converted to an integer value.
832 IntegerType *NTy = cast<IntegerType>(FromVal->getType());
834 // If this is a big-endian system and the load is narrower than the
835 // full alloca type, we need to do a shift to get the right bits.
837 if (DL.isBigEndian()) {
838 // On big-endian machines, the lowest bit is stored at the bit offset
839 // from the pointer given by getTypeStoreSizeInBits. This matters for
840 // integers with a bitwidth that is not a multiple of 8.
841 ShAmt = DL.getTypeStoreSizeInBits(NTy) -
842 DL.getTypeStoreSizeInBits(ToType) - Offset;
847 // Note: we support negative bitwidths (with shl) which are not defined.
848 // We do this to support (f.e.) loads off the end of a structure where
849 // only some bits are used.
850 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
851 FromVal = Builder.CreateLShr(FromVal,
852 ConstantInt::get(FromVal->getType(), ShAmt));
853 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
854 FromVal = Builder.CreateShl(FromVal,
855 ConstantInt::get(FromVal->getType(), -ShAmt));
857 // Finally, unconditionally truncate the integer to the right width.
858 unsigned LIBitWidth = DL.getTypeSizeInBits(ToType);
859 if (LIBitWidth < NTy->getBitWidth())
861 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
863 else if (LIBitWidth > NTy->getBitWidth())
865 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
868 // If the result is an integer, this is a trunc or bitcast.
869 if (ToType->isIntegerTy()) {
871 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
872 // Just do a bitcast, we know the sizes match up.
873 FromVal = Builder.CreateBitCast(FromVal, ToType);
875 // Otherwise must be a pointer.
876 FromVal = Builder.CreateIntToPtr(FromVal, ToType);
878 assert(FromVal->getType() == ToType && "Didn't convert right?");
882 /// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
883 /// or vector value "Old" at the offset specified by Offset.
885 /// This happens when we are converting an "integer union" to a
886 /// single integer scalar, or when we are converting a "vector union" to a
887 /// vector with insert/extractelement instructions.
889 /// Offset is an offset from the original alloca, in bits that need to be
890 /// shifted to the right.
892 /// NonConstantIdx is an index value if there was a GEP with a non-constant
893 /// index value. If this is 0 then all GEPs used to find this insert address
895 Value *ConvertToScalarInfo::
896 ConvertScalar_InsertValue(Value *SV, Value *Old,
897 uint64_t Offset, Value* NonConstantIdx,
898 IRBuilder<> &Builder) {
899 // Convert the stored type to the actual type, shift it left to insert
900 // then 'or' into place.
901 Type *AllocaType = Old->getType();
902 LLVMContext &Context = Old->getContext();
904 if (VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
905 uint64_t VecSize = DL.getTypeAllocSizeInBits(VTy);
906 uint64_t ValSize = DL.getTypeAllocSizeInBits(SV->getType());
908 // Changing the whole vector with memset or with an access of a different
910 if (ValSize == VecSize)
911 return Builder.CreateBitCast(SV, AllocaType);
913 // Must be an element insertion.
914 Type *EltTy = VTy->getElementType();
915 if (SV->getType() != EltTy)
916 SV = Builder.CreateBitCast(SV, EltTy);
917 uint64_t EltSize = DL.getTypeAllocSizeInBits(EltTy);
918 unsigned Elt = Offset/EltSize;
920 if (NonConstantIdx) {
922 Idx = Builder.CreateAdd(NonConstantIdx,
923 Builder.getInt32(Elt),
926 Idx = NonConstantIdx;
928 Idx = Builder.getInt32(Elt);
929 return Builder.CreateInsertElement(Old, SV, Idx);
932 // If SV is a first-class aggregate value, insert each value recursively.
933 if (StructType *ST = dyn_cast<StructType>(SV->getType())) {
934 assert(!NonConstantIdx &&
935 "Dynamic indexing into struct types not supported");
936 const StructLayout &Layout = *DL.getStructLayout(ST);
937 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
938 Value *Elt = Builder.CreateExtractValue(SV, i);
939 Old = ConvertScalar_InsertValue(Elt, Old,
940 Offset+Layout.getElementOffsetInBits(i),
946 if (ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
947 assert(!NonConstantIdx &&
948 "Dynamic indexing into array types not supported");
949 uint64_t EltSize = DL.getTypeAllocSizeInBits(AT->getElementType());
950 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
951 Value *Elt = Builder.CreateExtractValue(SV, i);
952 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, 0, Builder);
957 // If SV is a float, convert it to the appropriate integer type.
958 // If it is a pointer, do the same.
959 unsigned SrcWidth = DL.getTypeSizeInBits(SV->getType());
960 unsigned DestWidth = DL.getTypeSizeInBits(AllocaType);
961 unsigned SrcStoreWidth = DL.getTypeStoreSizeInBits(SV->getType());
962 unsigned DestStoreWidth = DL.getTypeStoreSizeInBits(AllocaType);
963 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
964 SV = Builder.CreateBitCast(SV, IntegerType::get(SV->getContext(),SrcWidth));
965 else if (SV->getType()->isPointerTy())
966 SV = Builder.CreatePtrToInt(SV, DL.getIntPtrType(SV->getType()));
968 // Zero extend or truncate the value if needed.
969 if (SV->getType() != AllocaType) {
970 if (SV->getType()->getPrimitiveSizeInBits() <
971 AllocaType->getPrimitiveSizeInBits())
972 SV = Builder.CreateZExt(SV, AllocaType);
974 // Truncation may be needed if storing more than the alloca can hold
975 // (undefined behavior).
976 SV = Builder.CreateTrunc(SV, AllocaType);
977 SrcWidth = DestWidth;
978 SrcStoreWidth = DestStoreWidth;
982 // If this is a big-endian system and the store is narrower than the
983 // full alloca type, we need to do a shift to get the right bits.
985 if (DL.isBigEndian()) {
986 // On big-endian machines, the lowest bit is stored at the bit offset
987 // from the pointer given by getTypeStoreSizeInBits. This matters for
988 // integers with a bitwidth that is not a multiple of 8.
989 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
994 // Note: we support negative bitwidths (with shr) which are not defined.
995 // We do this to support (f.e.) stores off the end of a structure where
996 // only some bits in the structure are set.
997 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
998 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
999 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(), ShAmt));
1001 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1002 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(), -ShAmt));
1003 Mask = Mask.lshr(-ShAmt);
1006 // Mask out the bits we are about to insert from the old value, and or
1008 if (SrcWidth != DestWidth) {
1009 assert(DestWidth > SrcWidth);
1010 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
1011 SV = Builder.CreateOr(Old, SV, "ins");
1017 //===----------------------------------------------------------------------===//
1019 //===----------------------------------------------------------------------===//
1022 bool SROA::runOnFunction(Function &F) {
1023 if (skipOptnoneFunction(F))
1026 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1027 DL = DLP ? &DLP->getDataLayout() : 0;
1029 bool Changed = performPromotion(F);
1031 // FIXME: ScalarRepl currently depends on DataLayout 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 (!DL) 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 (SmallVectorImpl<DbgDeclareInst *>::iterator I = DDIs.begin(),
1074 E = DDIs.end(); I != E; ++I) {
1075 DbgDeclareInst *DDI = *I;
1076 DDI->eraseFromParent();
1078 for (SmallVectorImpl<DbgValueInst *>::iterator I = DVIs.begin(),
1079 E = DVIs.end(); I != E; ++I) {
1080 DbgValueInst *DVI = *I;
1081 DVI->eraseFromParent();
1085 bool isInstInList(Instruction *I,
1086 const SmallVectorImpl<Instruction*> &Insts) const override {
1087 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1088 return LI->getOperand(0) == AI;
1089 return cast<StoreInst>(I)->getPointerOperand() == AI;
1092 void updateDebugInfo(Instruction *Inst) const override {
1093 for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
1094 E = DDIs.end(); I != E; ++I) {
1095 DbgDeclareInst *DDI = *I;
1096 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1097 ConvertDebugDeclareToDebugValue(DDI, SI, *DIB);
1098 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1099 ConvertDebugDeclareToDebugValue(DDI, LI, *DIB);
1101 for (SmallVectorImpl<DbgValueInst *>::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 DataLayout *DL) {
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(), DL))
1155 if (!FDerefable && !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
1156 LI->getAlignment(), DL))
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 DataLayout *DL) {
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, DL))
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 DataLayout *DL) {
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, DL);
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, DL))
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, DL))
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<DominatorTreeWrapperPass>().getDomTree();
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, DL))
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 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
1469 // which runs on all of the alloca instructions in the entry block, removing
1470 // them if they are only used by getelementptr instructions.
1472 bool SROA::performScalarRepl(Function &F) {
1473 std::vector<AllocaInst*> WorkList;
1475 // Scan the entry basic block, adding allocas to the worklist.
1476 BasicBlock &BB = F.getEntryBlock();
1477 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
1478 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
1479 WorkList.push_back(A);
1481 // Process the worklist
1482 bool Changed = false;
1483 while (!WorkList.empty()) {
1484 AllocaInst *AI = WorkList.back();
1485 WorkList.pop_back();
1487 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
1488 // with unused elements.
1489 if (AI->use_empty()) {
1490 AI->eraseFromParent();
1495 // If this alloca is impossible for us to promote, reject it early.
1496 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
1499 // Check to see if we can perform the core SROA transformation. We cannot
1500 // transform the allocation instruction if it is an array allocation
1501 // (allocations OF arrays are ok though), and an allocation of a scalar
1502 // value cannot be decomposed at all.
1503 uint64_t AllocaSize = DL->getTypeAllocSize(AI->getAllocatedType());
1505 // Do not promote [0 x %struct].
1506 if (AllocaSize == 0) continue;
1508 // Do not promote any struct whose size is too big.
1509 if (AllocaSize > SRThreshold) continue;
1511 // If the alloca looks like a good candidate for scalar replacement, and if
1512 // all its users can be transformed, then split up the aggregate into its
1513 // separate elements.
1514 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
1515 DoScalarReplacement(AI, WorkList);
1520 // If we can turn this aggregate value (potentially with casts) into a
1521 // simple scalar value that can be mem2reg'd into a register value.
1522 // IsNotTrivial tracks whether this is something that mem2reg could have
1523 // promoted itself. If so, we don't want to transform it needlessly. Note
1524 // that we can't just check based on the type: the alloca may be of an i32
1525 // but that has pointer arithmetic to set byte 3 of it or something.
1526 if (AllocaInst *NewAI = ConvertToScalarInfo(
1527 (unsigned)AllocaSize, *DL, ScalarLoadThreshold).TryConvert(AI)) {
1528 NewAI->takeName(AI);
1529 AI->eraseFromParent();
1535 // Otherwise, couldn't process this alloca.
1541 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1542 /// predicate, do SROA now.
1543 void SROA::DoScalarReplacement(AllocaInst *AI,
1544 std::vector<AllocaInst*> &WorkList) {
1545 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
1546 SmallVector<AllocaInst*, 32> ElementAllocas;
1547 if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1548 ElementAllocas.reserve(ST->getNumContainedTypes());
1549 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
1550 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
1552 AI->getName() + "." + Twine(i), AI);
1553 ElementAllocas.push_back(NA);
1554 WorkList.push_back(NA); // Add to worklist for recursive processing
1557 ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
1558 ElementAllocas.reserve(AT->getNumElements());
1559 Type *ElTy = AT->getElementType();
1560 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1561 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
1562 AI->getName() + "." + Twine(i), AI);
1563 ElementAllocas.push_back(NA);
1564 WorkList.push_back(NA); // Add to worklist for recursive processing
1568 // Now that we have created the new alloca instructions, rewrite all the
1569 // uses of the old alloca.
1570 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
1572 // Now erase any instructions that were made dead while rewriting the alloca.
1573 DeleteDeadInstructions();
1574 AI->eraseFromParent();
1579 /// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1580 /// recursively including all their operands that become trivially dead.
1581 void SROA::DeleteDeadInstructions() {
1582 while (!DeadInsts.empty()) {
1583 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
1585 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1586 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1587 // Zero out the operand and see if it becomes trivially dead.
1588 // (But, don't add allocas to the dead instruction list -- they are
1589 // already on the worklist and will be deleted separately.)
1591 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1592 DeadInsts.push_back(U);
1595 I->eraseFromParent();
1599 /// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1600 /// performing scalar replacement of alloca AI. The results are flagged in
1601 /// the Info parameter. Offset indicates the position within AI that is
1602 /// referenced by this instruction.
1603 void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
1605 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1606 Instruction *User = cast<Instruction>(*UI);
1608 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1609 isSafeForScalarRepl(BC, Offset, Info);
1610 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1611 uint64_t GEPOffset = Offset;
1612 isSafeGEP(GEPI, GEPOffset, Info);
1614 isSafeForScalarRepl(GEPI, GEPOffset, Info);
1615 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1616 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1618 return MarkUnsafe(Info, User);
1619 if (Length->isNegative())
1620 return MarkUnsafe(Info, User);
1622 isSafeMemAccess(Offset, Length->getZExtValue(), 0,
1623 UI.getOperandNo() == 0, Info, MI,
1624 true /*AllowWholeAccess*/);
1625 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1626 if (!LI->isSimple())
1627 return MarkUnsafe(Info, User);
1628 Type *LIType = LI->getType();
1629 isSafeMemAccess(Offset, DL->getTypeAllocSize(LIType),
1630 LIType, false, Info, LI, true /*AllowWholeAccess*/);
1631 Info.hasALoadOrStore = true;
1633 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1634 // Store is ok if storing INTO the pointer, not storing the pointer
1635 if (!SI->isSimple() || SI->getOperand(0) == I)
1636 return MarkUnsafe(Info, User);
1638 Type *SIType = SI->getOperand(0)->getType();
1639 isSafeMemAccess(Offset, DL->getTypeAllocSize(SIType),
1640 SIType, true, Info, SI, true /*AllowWholeAccess*/);
1641 Info.hasALoadOrStore = true;
1642 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
1643 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1644 II->getIntrinsicID() != Intrinsic::lifetime_end)
1645 return MarkUnsafe(Info, User);
1646 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1647 isSafePHISelectUseForScalarRepl(User, Offset, Info);
1649 return MarkUnsafe(Info, User);
1651 if (Info.isUnsafe) return;
1656 /// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
1657 /// derived from the alloca, we can often still split the alloca into elements.
1658 /// This is useful if we have a large alloca where one element is phi'd
1659 /// together somewhere: we can SRoA and promote all the other elements even if
1660 /// we end up not being able to promote this one.
1662 /// All we require is that the uses of the PHI do not index into other parts of
1663 /// the alloca. The most important use case for this is single load and stores
1664 /// that are PHI'd together, which can happen due to code sinking.
1665 void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
1667 // If we've already checked this PHI, don't do it again.
1668 if (PHINode *PN = dyn_cast<PHINode>(I))
1669 if (!Info.CheckedPHIs.insert(PN))
1672 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1673 Instruction *User = cast<Instruction>(*UI);
1675 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1676 isSafePHISelectUseForScalarRepl(BC, Offset, Info);
1677 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1678 // Only allow "bitcast" GEPs for simplicity. We could generalize this,
1679 // but would have to prove that we're staying inside of an element being
1681 if (!GEPI->hasAllZeroIndices())
1682 return MarkUnsafe(Info, User);
1683 isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
1684 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1685 if (!LI->isSimple())
1686 return MarkUnsafe(Info, User);
1687 Type *LIType = LI->getType();
1688 isSafeMemAccess(Offset, DL->getTypeAllocSize(LIType),
1689 LIType, false, Info, LI, false /*AllowWholeAccess*/);
1690 Info.hasALoadOrStore = true;
1692 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1693 // Store is ok if storing INTO the pointer, not storing the pointer
1694 if (!SI->isSimple() || SI->getOperand(0) == I)
1695 return MarkUnsafe(Info, User);
1697 Type *SIType = SI->getOperand(0)->getType();
1698 isSafeMemAccess(Offset, DL->getTypeAllocSize(SIType),
1699 SIType, true, Info, SI, false /*AllowWholeAccess*/);
1700 Info.hasALoadOrStore = true;
1701 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1702 isSafePHISelectUseForScalarRepl(User, Offset, Info);
1704 return MarkUnsafe(Info, User);
1706 if (Info.isUnsafe) return;
1710 /// isSafeGEP - Check if a GEP instruction can be handled for scalar
1711 /// replacement. It is safe when all the indices are constant, in-bounds
1712 /// references, and when the resulting offset corresponds to an element within
1713 /// the alloca type. The results are flagged in the Info parameter. Upon
1714 /// return, Offset is adjusted as specified by the GEP indices.
1715 void SROA::isSafeGEP(GetElementPtrInst *GEPI,
1716 uint64_t &Offset, AllocaInfo &Info) {
1717 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1720 bool NonConstant = false;
1721 unsigned NonConstantIdxSize = 0;
1723 // Walk through the GEP type indices, checking the types that this indexes
1725 for (; GEPIt != E; ++GEPIt) {
1726 // Ignore struct elements, no extra checking needed for these.
1727 if ((*GEPIt)->isStructTy())
1730 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1732 return MarkUnsafe(Info, GEPI);
1735 // Compute the offset due to this GEP and check if the alloca has a
1736 // component element at that offset.
1737 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1738 // If this GEP is non-constant then the last operand must have been a
1739 // dynamic index into a vector. Pop this now as it has no impact on the
1740 // constant part of the offset.
1743 Offset += DL->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
1744 if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset,
1745 NonConstantIdxSize))
1746 MarkUnsafe(Info, GEPI);
1749 /// isHomogeneousAggregate - Check if type T is a struct or array containing
1750 /// elements of the same type (which is always true for arrays). If so,
1751 /// return true with NumElts and EltTy set to the number of elements and the
1752 /// element type, respectively.
1753 static bool isHomogeneousAggregate(Type *T, unsigned &NumElts,
1755 if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
1756 NumElts = AT->getNumElements();
1757 EltTy = (NumElts == 0 ? 0 : AT->getElementType());
1760 if (StructType *ST = dyn_cast<StructType>(T)) {
1761 NumElts = ST->getNumContainedTypes();
1762 EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
1763 for (unsigned n = 1; n < NumElts; ++n) {
1764 if (ST->getContainedType(n) != EltTy)
1772 /// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1773 /// "homogeneous" aggregates with the same element type and number of elements.
1774 static bool isCompatibleAggregate(Type *T1, Type *T2) {
1778 unsigned NumElts1, NumElts2;
1779 Type *EltTy1, *EltTy2;
1780 if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1781 isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1782 NumElts1 == NumElts2 &&
1789 /// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1790 /// alloca or has an offset and size that corresponds to a component element
1791 /// within it. The offset checked here may have been formed from a GEP with a
1792 /// pointer bitcasted to a different type.
1794 /// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
1795 /// unit. If false, it only allows accesses known to be in a single element.
1796 void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
1797 Type *MemOpType, bool isStore,
1798 AllocaInfo &Info, Instruction *TheAccess,
1799 bool AllowWholeAccess) {
1800 // Check if this is a load/store of the entire alloca.
1801 if (Offset == 0 && AllowWholeAccess &&
1802 MemSize == DL->getTypeAllocSize(Info.AI->getAllocatedType())) {
1803 // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1804 // loads/stores (which are essentially the same as the MemIntrinsics with
1805 // regard to copying padding between elements). But, if an alloca is
1806 // flagged as both a source and destination of such operations, we'll need
1807 // to check later for padding between elements.
1808 if (!MemOpType || MemOpType->isIntegerTy()) {
1810 Info.isMemCpyDst = true;
1812 Info.isMemCpySrc = true;
1815 // This is also safe for references using a type that is compatible with
1816 // the type of the alloca, so that loads/stores can be rewritten using
1817 // insertvalue/extractvalue.
1818 if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
1819 Info.hasSubelementAccess = true;
1823 // Check if the offset/size correspond to a component within the alloca type.
1824 Type *T = Info.AI->getAllocatedType();
1825 if (TypeHasComponent(T, Offset, MemSize)) {
1826 Info.hasSubelementAccess = true;
1830 return MarkUnsafe(Info, TheAccess);
1833 /// TypeHasComponent - Return true if T has a component type with the
1834 /// specified offset and size. If Size is zero, do not check the size.
1835 bool SROA::TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size) {
1838 if (StructType *ST = dyn_cast<StructType>(T)) {
1839 const StructLayout *Layout = DL->getStructLayout(ST);
1840 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1841 EltTy = ST->getContainedType(EltIdx);
1842 EltSize = DL->getTypeAllocSize(EltTy);
1843 Offset -= Layout->getElementOffset(EltIdx);
1844 } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
1845 EltTy = AT->getElementType();
1846 EltSize = DL->getTypeAllocSize(EltTy);
1847 if (Offset >= AT->getNumElements() * EltSize)
1850 } else if (VectorType *VT = dyn_cast<VectorType>(T)) {
1851 EltTy = VT->getElementType();
1852 EltSize = DL->getTypeAllocSize(EltTy);
1853 if (Offset >= VT->getNumElements() * EltSize)
1859 if (Offset == 0 && (Size == 0 || EltSize == Size))
1861 // Check if the component spans multiple elements.
1862 if (Offset + Size > EltSize)
1864 return TypeHasComponent(EltTy, Offset, Size);
1867 /// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1868 /// the instruction I, which references it, to use the separate elements.
1869 /// Offset indicates the position within AI that is referenced by this
1871 void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1872 SmallVectorImpl<AllocaInst *> &NewElts) {
1873 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
1874 Use &TheUse = UI.getUse();
1875 Instruction *User = cast<Instruction>(*UI++);
1877 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1878 RewriteBitCast(BC, AI, Offset, NewElts);
1882 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1883 RewriteGEP(GEPI, AI, Offset, NewElts);
1887 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1888 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1889 uint64_t MemSize = Length->getZExtValue();
1891 MemSize == DL->getTypeAllocSize(AI->getAllocatedType()))
1892 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
1893 // Otherwise the intrinsic can only touch a single element and the
1894 // address operand will be updated, so nothing else needs to be done.
1898 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
1899 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
1900 II->getIntrinsicID() == Intrinsic::lifetime_end) {
1901 RewriteLifetimeIntrinsic(II, AI, Offset, NewElts);
1906 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1907 Type *LIType = LI->getType();
1909 if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
1911 // %res = load { i32, i32 }* %alloc
1913 // %load.0 = load i32* %alloc.0
1914 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1915 // %load.1 = load i32* %alloc.1
1916 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1917 // (Also works for arrays instead of structs)
1918 Value *Insert = UndefValue::get(LIType);
1919 IRBuilder<> Builder(LI);
1920 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1921 Value *Load = Builder.CreateLoad(NewElts[i], "load");
1922 Insert = Builder.CreateInsertValue(Insert, Load, i, "insert");
1924 LI->replaceAllUsesWith(Insert);
1925 DeadInsts.push_back(LI);
1926 } else if (LIType->isIntegerTy() &&
1927 DL->getTypeAllocSize(LIType) ==
1928 DL->getTypeAllocSize(AI->getAllocatedType())) {
1929 // If this is a load of the entire alloca to an integer, rewrite it.
1930 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1935 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1936 Value *Val = SI->getOperand(0);
1937 Type *SIType = Val->getType();
1938 if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
1940 // store { i32, i32 } %val, { i32, i32 }* %alloc
1942 // %val.0 = extractvalue { i32, i32 } %val, 0
1943 // store i32 %val.0, i32* %alloc.0
1944 // %val.1 = extractvalue { i32, i32 } %val, 1
1945 // store i32 %val.1, i32* %alloc.1
1946 // (Also works for arrays instead of structs)
1947 IRBuilder<> Builder(SI);
1948 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1949 Value *Extract = Builder.CreateExtractValue(Val, i, Val->getName());
1950 Builder.CreateStore(Extract, NewElts[i]);
1952 DeadInsts.push_back(SI);
1953 } else if (SIType->isIntegerTy() &&
1954 DL->getTypeAllocSize(SIType) ==
1955 DL->getTypeAllocSize(AI->getAllocatedType())) {
1956 // If this is a store of the entire alloca from an integer, rewrite it.
1957 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1962 if (isa<SelectInst>(User) || isa<PHINode>(User)) {
1963 // If we have a PHI user of the alloca itself (as opposed to a GEP or
1964 // bitcast) we have to rewrite it. GEP and bitcast uses will be RAUW'd to
1966 if (!isa<AllocaInst>(I)) continue;
1968 assert(Offset == 0 && NewElts[0] &&
1969 "Direct alloca use should have a zero offset");
1971 // If we have a use of the alloca, we know the derived uses will be
1972 // utilizing just the first element of the scalarized result. Insert a
1973 // bitcast of the first alloca before the user as required.
1974 AllocaInst *NewAI = NewElts[0];
1975 BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
1976 NewAI->moveBefore(BCI);
1983 /// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1984 /// and recursively continue updating all of its uses.
1985 void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1986 SmallVectorImpl<AllocaInst *> &NewElts) {
1987 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1988 if (BC->getOperand(0) != AI)
1991 // The bitcast references the original alloca. Replace its uses with
1992 // references to the alloca containing offset zero (which is normally at
1993 // index zero, but might not be in cases involving structs with elements
1995 Type *T = AI->getAllocatedType();
1996 uint64_t EltOffset = 0;
1998 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
1999 Instruction *Val = NewElts[Idx];
2000 if (Val->getType() != BC->getDestTy()) {
2001 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
2004 BC->replaceAllUsesWith(Val);
2005 DeadInsts.push_back(BC);
2008 /// FindElementAndOffset - Return the index of the element containing Offset
2009 /// within the specified type, which must be either a struct or an array.
2010 /// Sets T to the type of the element and Offset to the offset within that
2011 /// element. IdxTy is set to the type of the index result to be used in a
2012 /// GEP instruction.
2013 uint64_t SROA::FindElementAndOffset(Type *&T, uint64_t &Offset,
2016 if (StructType *ST = dyn_cast<StructType>(T)) {
2017 const StructLayout *Layout = DL->getStructLayout(ST);
2018 Idx = Layout->getElementContainingOffset(Offset);
2019 T = ST->getContainedType(Idx);
2020 Offset -= Layout->getElementOffset(Idx);
2021 IdxTy = Type::getInt32Ty(T->getContext());
2023 } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
2024 T = AT->getElementType();
2025 uint64_t EltSize = DL->getTypeAllocSize(T);
2026 Idx = Offset / EltSize;
2027 Offset -= Idx * EltSize;
2028 IdxTy = Type::getInt64Ty(T->getContext());
2031 VectorType *VT = cast<VectorType>(T);
2032 T = VT->getElementType();
2033 uint64_t EltSize = DL->getTypeAllocSize(T);
2034 Idx = Offset / EltSize;
2035 Offset -= Idx * EltSize;
2036 IdxTy = Type::getInt64Ty(T->getContext());
2040 /// RewriteGEP - Check if this GEP instruction moves the pointer across
2041 /// elements of the alloca that are being split apart, and if so, rewrite
2042 /// the GEP to be relative to the new element.
2043 void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
2044 SmallVectorImpl<AllocaInst *> &NewElts) {
2045 uint64_t OldOffset = Offset;
2046 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
2047 // If the GEP was dynamic then it must have been a dynamic vector lookup.
2048 // In this case, it must be the last GEP operand which is dynamic so keep that
2049 // aside until we've found the constant GEP offset then add it back in at the
2051 Value* NonConstantIdx = 0;
2052 if (!GEPI->hasAllConstantIndices())
2053 NonConstantIdx = Indices.pop_back_val();
2054 Offset += DL->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
2056 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
2058 Type *T = AI->getAllocatedType();
2060 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
2061 if (GEPI->getOperand(0) == AI)
2062 OldIdx = ~0ULL; // Force the GEP to be rewritten.
2064 T = AI->getAllocatedType();
2065 uint64_t EltOffset = Offset;
2066 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
2068 // If this GEP does not move the pointer across elements of the alloca
2069 // being split, then it does not needs to be rewritten.
2073 Type *i32Ty = Type::getInt32Ty(AI->getContext());
2074 SmallVector<Value*, 8> NewArgs;
2075 NewArgs.push_back(Constant::getNullValue(i32Ty));
2076 while (EltOffset != 0) {
2077 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
2078 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
2080 if (NonConstantIdx) {
2082 // This GEP has a dynamic index. We need to add "i32 0" to index through
2083 // any structs or arrays in the original type until we get to the vector
2085 while (!isa<VectorType>(GepTy)) {
2086 NewArgs.push_back(Constant::getNullValue(i32Ty));
2087 GepTy = cast<CompositeType>(GepTy)->getTypeAtIndex(0U);
2089 NewArgs.push_back(NonConstantIdx);
2091 Instruction *Val = NewElts[Idx];
2092 if (NewArgs.size() > 1) {
2093 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs, "", GEPI);
2094 Val->takeName(GEPI);
2096 if (Val->getType() != GEPI->getType())
2097 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
2098 GEPI->replaceAllUsesWith(Val);
2099 DeadInsts.push_back(GEPI);
2102 /// RewriteLifetimeIntrinsic - II is a lifetime.start/lifetime.end. Rewrite it
2103 /// to mark the lifetime of the scalarized memory.
2104 void SROA::RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
2106 SmallVectorImpl<AllocaInst *> &NewElts) {
2107 ConstantInt *OldSize = cast<ConstantInt>(II->getArgOperand(0));
2108 // Put matching lifetime markers on everything from Offset up to
2110 Type *AIType = AI->getAllocatedType();
2111 uint64_t NewOffset = Offset;
2113 uint64_t Idx = FindElementAndOffset(AIType, NewOffset, IdxTy);
2115 IRBuilder<> Builder(II);
2116 uint64_t Size = OldSize->getLimitedValue();
2119 // Splice the first element and index 'NewOffset' bytes in. SROA will
2120 // split the alloca again later.
2121 Value *V = Builder.CreateBitCast(NewElts[Idx], Builder.getInt8PtrTy());
2122 V = Builder.CreateGEP(V, Builder.getInt64(NewOffset));
2124 IdxTy = NewElts[Idx]->getAllocatedType();
2125 uint64_t EltSize = DL->getTypeAllocSize(IdxTy) - NewOffset;
2126 if (EltSize > Size) {
2132 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
2133 Builder.CreateLifetimeStart(V, Builder.getInt64(EltSize));
2135 Builder.CreateLifetimeEnd(V, Builder.getInt64(EltSize));
2139 for (; Idx != NewElts.size() && Size; ++Idx) {
2140 IdxTy = NewElts[Idx]->getAllocatedType();
2141 uint64_t EltSize = DL->getTypeAllocSize(IdxTy);
2142 if (EltSize > Size) {
2148 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
2149 Builder.CreateLifetimeStart(NewElts[Idx],
2150 Builder.getInt64(EltSize));
2152 Builder.CreateLifetimeEnd(NewElts[Idx],
2153 Builder.getInt64(EltSize));
2155 DeadInsts.push_back(II);
2158 /// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
2159 /// Rewrite it to copy or set the elements of the scalarized memory.
2161 SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
2163 SmallVectorImpl<AllocaInst *> &NewElts) {
2164 // If this is a memcpy/memmove, construct the other pointer as the
2165 // appropriate type. The "Other" pointer is the pointer that goes to memory
2166 // that doesn't have anything to do with the alloca that we are promoting. For
2167 // memset, this Value* stays null.
2168 Value *OtherPtr = 0;
2169 unsigned MemAlignment = MI->getAlignment();
2170 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
2171 if (Inst == MTI->getRawDest())
2172 OtherPtr = MTI->getRawSource();
2174 assert(Inst == MTI->getRawSource());
2175 OtherPtr = MTI->getRawDest();
2179 // If there is an other pointer, we want to convert it to the same pointer
2180 // type as AI has, so we can GEP through it safely.
2182 unsigned AddrSpace =
2183 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
2185 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
2186 // optimization, but it's also required to detect the corner case where
2187 // both pointer operands are referencing the same memory, and where
2188 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
2189 // function is only called for mem intrinsics that access the whole
2190 // aggregate, so non-zero GEPs are not an issue here.)
2191 OtherPtr = OtherPtr->stripPointerCasts();
2193 // Copying the alloca to itself is a no-op: just delete it.
2194 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
2195 // This code will run twice for a no-op memcpy -- once for each operand.
2196 // Put only one reference to MI on the DeadInsts list.
2197 for (SmallVectorImpl<Value *>::const_iterator I = DeadInsts.begin(),
2198 E = DeadInsts.end(); I != E; ++I)
2199 if (*I == MI) return;
2200 DeadInsts.push_back(MI);
2204 // If the pointer is not the right type, insert a bitcast to the right
2207 PointerType::get(AI->getType()->getElementType(), AddrSpace);
2209 if (OtherPtr->getType() != NewTy)
2210 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
2213 // Process each element of the aggregate.
2214 bool SROADest = MI->getRawDest() == Inst;
2216 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
2218 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2219 // If this is a memcpy/memmove, emit a GEP of the other element address.
2220 Value *OtherElt = 0;
2221 unsigned OtherEltAlign = MemAlignment;
2224 Value *Idx[2] = { Zero,
2225 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
2226 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx,
2227 OtherPtr->getName()+"."+Twine(i),
2230 PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
2231 Type *OtherTy = OtherPtrTy->getElementType();
2232 if (StructType *ST = dyn_cast<StructType>(OtherTy)) {
2233 EltOffset = DL->getStructLayout(ST)->getElementOffset(i);
2235 Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
2236 EltOffset = DL->getTypeAllocSize(EltTy)*i;
2239 // The alignment of the other pointer is the guaranteed alignment of the
2240 // element, which is affected by both the known alignment of the whole
2241 // mem intrinsic and the alignment of the element. If the alignment of
2242 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
2243 // known alignment is just 4 bytes.
2244 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
2247 Value *EltPtr = NewElts[i];
2248 Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
2250 // If we got down to a scalar, insert a load or store as appropriate.
2251 if (EltTy->isSingleValueType()) {
2252 if (isa<MemTransferInst>(MI)) {
2254 // From Other to Alloca.
2255 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
2256 new StoreInst(Elt, EltPtr, MI);
2258 // From Alloca to Other.
2259 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
2260 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
2264 assert(isa<MemSetInst>(MI));
2266 // If the stored element is zero (common case), just store a null
2269 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
2271 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
2273 // If EltTy is a vector type, get the element type.
2274 Type *ValTy = EltTy->getScalarType();
2276 // Construct an integer with the right value.
2277 unsigned EltSize = DL->getTypeSizeInBits(ValTy);
2278 APInt OneVal(EltSize, CI->getZExtValue());
2279 APInt TotalVal(OneVal);
2281 for (unsigned i = 0; 8*i < EltSize; ++i) {
2282 TotalVal = TotalVal.shl(8);
2286 // Convert the integer value to the appropriate type.
2287 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
2288 if (ValTy->isPointerTy())
2289 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
2290 else if (ValTy->isFloatingPointTy())
2291 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
2292 assert(StoreVal->getType() == ValTy && "Type mismatch!");
2294 // If the requested value was a vector constant, create it.
2295 if (EltTy->isVectorTy()) {
2296 unsigned NumElts = cast<VectorType>(EltTy)->getNumElements();
2297 StoreVal = ConstantVector::getSplat(NumElts, StoreVal);
2300 new StoreInst(StoreVal, EltPtr, MI);
2303 // Otherwise, if we're storing a byte variable, use a memset call for
2307 unsigned EltSize = DL->getTypeAllocSize(EltTy);
2311 IRBuilder<> Builder(MI);
2313 // Finally, insert the meminst for this element.
2314 if (isa<MemSetInst>(MI)) {
2315 Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
2318 assert(isa<MemTransferInst>(MI));
2319 Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr
2320 Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr
2322 if (isa<MemCpyInst>(MI))
2323 Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
2325 Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
2328 DeadInsts.push_back(MI);
2331 /// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
2332 /// overwrites the entire allocation. Extract out the pieces of the stored
2333 /// integer and store them individually.
2335 SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
2336 SmallVectorImpl<AllocaInst *> &NewElts) {
2337 // Extract each element out of the integer according to its structure offset
2338 // and store the element value to the individual alloca.
2339 Value *SrcVal = SI->getOperand(0);
2340 Type *AllocaEltTy = AI->getAllocatedType();
2341 uint64_t AllocaSizeBits = DL->getTypeAllocSizeInBits(AllocaEltTy);
2343 IRBuilder<> Builder(SI);
2345 // Handle tail padding by extending the operand
2346 if (DL->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
2347 SrcVal = Builder.CreateZExt(SrcVal,
2348 IntegerType::get(SI->getContext(), AllocaSizeBits));
2350 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
2353 // There are two forms here: AI could be an array or struct. Both cases
2354 // have different ways to compute the element offset.
2355 if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2356 const StructLayout *Layout = DL->getStructLayout(EltSTy);
2358 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2359 // Get the number of bits to shift SrcVal to get the value.
2360 Type *FieldTy = EltSTy->getElementType(i);
2361 uint64_t Shift = Layout->getElementOffsetInBits(i);
2363 if (DL->isBigEndian())
2364 Shift = AllocaSizeBits-Shift-DL->getTypeAllocSizeInBits(FieldTy);
2366 Value *EltVal = SrcVal;
2368 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
2369 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
2372 // Truncate down to an integer of the right size.
2373 uint64_t FieldSizeBits = DL->getTypeSizeInBits(FieldTy);
2375 // Ignore zero sized fields like {}, they obviously contain no data.
2376 if (FieldSizeBits == 0) continue;
2378 if (FieldSizeBits != AllocaSizeBits)
2379 EltVal = Builder.CreateTrunc(EltVal,
2380 IntegerType::get(SI->getContext(), FieldSizeBits));
2381 Value *DestField = NewElts[i];
2382 if (EltVal->getType() == FieldTy) {
2383 // Storing to an integer field of this size, just do it.
2384 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
2385 // Bitcast to the right element type (for fp/vector values).
2386 EltVal = Builder.CreateBitCast(EltVal, FieldTy);
2388 // Otherwise, bitcast the dest pointer (for aggregates).
2389 DestField = Builder.CreateBitCast(DestField,
2390 PointerType::getUnqual(EltVal->getType()));
2392 new StoreInst(EltVal, DestField, SI);
2396 ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
2397 Type *ArrayEltTy = ATy->getElementType();
2398 uint64_t ElementOffset = DL->getTypeAllocSizeInBits(ArrayEltTy);
2399 uint64_t ElementSizeBits = DL->getTypeSizeInBits(ArrayEltTy);
2403 if (DL->isBigEndian())
2404 Shift = AllocaSizeBits-ElementOffset;
2408 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2409 // Ignore zero sized fields like {}, they obviously contain no data.
2410 if (ElementSizeBits == 0) continue;
2412 Value *EltVal = SrcVal;
2414 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
2415 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
2418 // Truncate down to an integer of the right size.
2419 if (ElementSizeBits != AllocaSizeBits)
2420 EltVal = Builder.CreateTrunc(EltVal,
2421 IntegerType::get(SI->getContext(),
2423 Value *DestField = NewElts[i];
2424 if (EltVal->getType() == ArrayEltTy) {
2425 // Storing to an integer field of this size, just do it.
2426 } else if (ArrayEltTy->isFloatingPointTy() ||
2427 ArrayEltTy->isVectorTy()) {
2428 // Bitcast to the right element type (for fp/vector values).
2429 EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
2431 // Otherwise, bitcast the dest pointer (for aggregates).
2432 DestField = Builder.CreateBitCast(DestField,
2433 PointerType::getUnqual(EltVal->getType()));
2435 new StoreInst(EltVal, DestField, SI);
2437 if (DL->isBigEndian())
2438 Shift -= ElementOffset;
2440 Shift += ElementOffset;
2444 DeadInsts.push_back(SI);
2447 /// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
2448 /// an integer. Load the individual pieces to form the aggregate value.
2450 SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
2451 SmallVectorImpl<AllocaInst *> &NewElts) {
2452 // Extract each element out of the NewElts according to its structure offset
2453 // and form the result value.
2454 Type *AllocaEltTy = AI->getAllocatedType();
2455 uint64_t AllocaSizeBits = DL->getTypeAllocSizeInBits(AllocaEltTy);
2457 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
2460 // There are two forms here: AI could be an array or struct. Both cases
2461 // have different ways to compute the element offset.
2462 const StructLayout *Layout = 0;
2463 uint64_t ArrayEltBitOffset = 0;
2464 if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2465 Layout = DL->getStructLayout(EltSTy);
2467 Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
2468 ArrayEltBitOffset = DL->getTypeAllocSizeInBits(ArrayEltTy);
2472 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
2474 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2475 // Load the value from the alloca. If the NewElt is an aggregate, cast
2476 // the pointer to an integer of the same size before doing the load.
2477 Value *SrcField = NewElts[i];
2479 cast<PointerType>(SrcField->getType())->getElementType();
2480 uint64_t FieldSizeBits = DL->getTypeSizeInBits(FieldTy);
2482 // Ignore zero sized fields like {}, they obviously contain no data.
2483 if (FieldSizeBits == 0) continue;
2485 IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
2487 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
2488 !FieldTy->isVectorTy())
2489 SrcField = new BitCastInst(SrcField,
2490 PointerType::getUnqual(FieldIntTy),
2492 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
2494 // If SrcField is a fp or vector of the right size but that isn't an
2495 // integer type, bitcast to an integer so we can shift it.
2496 if (SrcField->getType() != FieldIntTy)
2497 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
2499 // Zero extend the field to be the same size as the final alloca so that
2500 // we can shift and insert it.
2501 if (SrcField->getType() != ResultVal->getType())
2502 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
2504 // Determine the number of bits to shift SrcField.
2506 if (Layout) // Struct case.
2507 Shift = Layout->getElementOffsetInBits(i);
2509 Shift = i*ArrayEltBitOffset;
2511 if (DL->isBigEndian())
2512 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
2515 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
2516 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
2519 // Don't create an 'or x, 0' on the first iteration.
2520 if (!isa<Constant>(ResultVal) ||
2521 !cast<Constant>(ResultVal)->isNullValue())
2522 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
2524 ResultVal = SrcField;
2527 // Handle tail padding by truncating the result
2528 if (DL->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
2529 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
2531 LI->replaceAllUsesWith(ResultVal);
2532 DeadInsts.push_back(LI);
2535 /// HasPadding - Return true if the specified type has any structure or
2536 /// alignment padding in between the elements that would be split apart
2537 /// by SROA; return false otherwise.
2538 static bool HasPadding(Type *Ty, const DataLayout &DL) {
2539 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2540 Ty = ATy->getElementType();
2541 return DL.getTypeSizeInBits(Ty) != DL.getTypeAllocSizeInBits(Ty);
2544 // SROA currently handles only Arrays and Structs.
2545 StructType *STy = cast<StructType>(Ty);
2546 const StructLayout *SL = DL.getStructLayout(STy);
2547 unsigned PrevFieldBitOffset = 0;
2548 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2549 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
2551 // Check to see if there is any padding between this element and the
2554 unsigned PrevFieldEnd =
2555 PrevFieldBitOffset+DL.getTypeSizeInBits(STy->getElementType(i-1));
2556 if (PrevFieldEnd < FieldBitOffset)
2559 PrevFieldBitOffset = FieldBitOffset;
2561 // Check for tail padding.
2562 if (unsigned EltCount = STy->getNumElements()) {
2563 unsigned PrevFieldEnd = PrevFieldBitOffset +
2564 DL.getTypeSizeInBits(STy->getElementType(EltCount-1));
2565 if (PrevFieldEnd < SL->getSizeInBits())
2571 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
2572 /// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
2573 /// or 1 if safe after canonicalization has been performed.
2574 bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
2575 // Loop over the use list of the alloca. We can only transform it if all of
2576 // the users are safe to transform.
2577 AllocaInfo Info(AI);
2579 isSafeForScalarRepl(AI, 0, Info);
2580 if (Info.isUnsafe) {
2581 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
2585 // Okay, we know all the users are promotable. If the aggregate is a memcpy
2586 // source and destination, we have to be careful. In particular, the memcpy
2587 // could be moving around elements that live in structure padding of the LLVM
2588 // types, but may actually be used. In these cases, we refuse to promote the
2590 if (Info.isMemCpySrc && Info.isMemCpyDst &&
2591 HasPadding(AI->getAllocatedType(), *DL))
2594 // If the alloca never has an access to just *part* of it, but is accessed
2595 // via loads and stores, then we should use ConvertToScalarInfo to promote
2596 // the alloca instead of promoting each piece at a time and inserting fission
2598 if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
2599 // If the struct/array just has one element, use basic SRoA.
2600 if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
2601 if (ST->getNumElements() > 1) return false;
2603 if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)