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
17 // often interact, especially for C++ programs. As such, iterating between
18 // SRoA, then Mem2Reg until we run out of things to promote works well.
20 //===----------------------------------------------------------------------===//
22 #define DEBUG_TYPE "scalarrepl"
23 #include "llvm/Transforms/Scalar.h"
24 #include "llvm/Constants.h"
25 #include "llvm/DerivedTypes.h"
26 #include "llvm/Function.h"
27 #include "llvm/GlobalVariable.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/IntrinsicInst.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Analysis/Dominators.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
35 #include "llvm/Transforms/Utils/Local.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/GetElementPtrTypeIterator.h"
39 #include "llvm/Support/IRBuilder.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/ADT/SmallVector.h"
43 #include "llvm/ADT/Statistic.h"
46 STATISTIC(NumReplaced, "Number of allocas broken up");
47 STATISTIC(NumPromoted, "Number of allocas promoted");
48 STATISTIC(NumConverted, "Number of aggregates converted to scalar");
49 STATISTIC(NumGlobals, "Number of allocas copied from constant global");
52 struct SROA : public FunctionPass {
53 static char ID; // Pass identification, replacement for typeid
54 explicit SROA(signed T = -1) : FunctionPass(ID) {
61 bool runOnFunction(Function &F);
63 bool performScalarRepl(Function &F);
64 bool performPromotion(Function &F);
66 // getAnalysisUsage - This pass does not require any passes, but we know it
67 // will not alter the CFG, so say so.
68 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
69 AU.addRequired<DominatorTree>();
70 AU.addRequired<DominanceFrontier>();
77 /// DeadInsts - Keep track of instructions we have made dead, so that
78 /// we can remove them after we are done working.
79 SmallVector<Value*, 32> DeadInsts;
81 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
82 /// information about the uses. All these fields are initialized to false
83 /// and set to true when something is learned.
85 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
88 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
91 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
95 : isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false) {}
100 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
102 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
104 void isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
106 void isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t &Offset,
108 void isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
109 const Type *MemOpType, bool isStore, AllocaInfo &Info);
110 bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
111 uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
114 void DoScalarReplacement(AllocaInst *AI,
115 std::vector<AllocaInst*> &WorkList);
116 void DeleteDeadInstructions();
118 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
119 SmallVector<AllocaInst*, 32> &NewElts);
120 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
121 SmallVector<AllocaInst*, 32> &NewElts);
122 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
123 SmallVector<AllocaInst*, 32> &NewElts);
124 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
126 SmallVector<AllocaInst*, 32> &NewElts);
127 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
128 SmallVector<AllocaInst*, 32> &NewElts);
129 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
130 SmallVector<AllocaInst*, 32> &NewElts);
132 static MemTransferInst *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
137 INITIALIZE_PASS(SROA, "scalarrepl",
138 "Scalar Replacement of Aggregates", false, false);
140 // Public interface to the ScalarReplAggregates pass
141 FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
142 return new SROA(Threshold);
146 //===----------------------------------------------------------------------===//
147 // Convert To Scalar Optimization.
148 //===----------------------------------------------------------------------===//
151 /// ConvertToScalarInfo - This class implements the "Convert To Scalar"
152 /// optimization, which scans the uses of an alloca and determines if it can
153 /// rewrite it in terms of a single new alloca that can be mem2reg'd.
154 class ConvertToScalarInfo {
155 /// AllocaSize - The size of the alloca being considered.
157 const TargetData &TD;
159 /// IsNotTrivial - This is set to true if there is some access to the object
160 /// which means that mem2reg can't promote it.
163 /// VectorTy - This tracks the type that we should promote the vector to if
164 /// it is possible to turn it into a vector. This starts out null, and if it
165 /// isn't possible to turn into a vector type, it gets set to VoidTy.
166 const Type *VectorTy;
168 /// HadAVector - True if there is at least one vector access to the alloca.
169 /// We don't want to turn random arrays into vectors and use vector element
170 /// insert/extract, but if there are element accesses to something that is
171 /// also declared as a vector, we do want to promote to a vector.
175 explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
176 : AllocaSize(Size), TD(td) {
177 IsNotTrivial = false;
182 AllocaInst *TryConvert(AllocaInst *AI);
185 bool CanConvertToScalar(Value *V, uint64_t Offset);
186 void MergeInType(const Type *In, uint64_t Offset);
187 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
189 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
190 uint64_t Offset, IRBuilder<> &Builder);
191 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
192 uint64_t Offset, IRBuilder<> &Builder);
194 } // end anonymous namespace.
197 /// IsVerbotenVectorType - Return true if this is a vector type ScalarRepl isn't
198 /// allowed to form. We do this to avoid MMX types, which is a complete hack,
199 /// but is required until the backend is fixed.
200 static bool IsVerbotenVectorType(const VectorType *VTy) {
201 // Reject all the MMX vector types.
202 switch (VTy->getNumElements()) {
203 default: return false;
204 case 1: return VTy->getElementType()->isIntegerTy(64);
205 case 2: return VTy->getElementType()->isIntegerTy(32);
206 case 4: return VTy->getElementType()->isIntegerTy(16);
207 case 8: return VTy->getElementType()->isIntegerTy(8);
212 /// TryConvert - Analyze the specified alloca, and if it is safe to do so,
213 /// rewrite it to be a new alloca which is mem2reg'able. This returns the new
214 /// alloca if possible or null if not.
215 AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
216 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
218 if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
221 // If we were able to find a vector type that can handle this with
222 // insert/extract elements, and if there was at least one use that had
223 // a vector type, promote this to a vector. We don't want to promote
224 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
225 // we just get a lot of insert/extracts. If at least one vector is
226 // involved, then we probably really do have a union of vector/array.
228 if (VectorTy && VectorTy->isVectorTy() && HadAVector &&
229 !IsVerbotenVectorType(cast<VectorType>(VectorTy))) {
230 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
231 << *VectorTy << '\n');
232 NewTy = VectorTy; // Use the vector type.
234 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
235 // Create and insert the integer alloca.
236 NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
238 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
239 ConvertUsesToScalar(AI, NewAI, 0);
243 /// MergeInType - Add the 'In' type to the accumulated vector type (VectorTy)
244 /// so far at the offset specified by Offset (which is specified in bytes).
246 /// There are two cases we handle here:
247 /// 1) A union of vector types of the same size and potentially its elements.
248 /// Here we turn element accesses into insert/extract element operations.
249 /// This promotes a <4 x float> with a store of float to the third element
250 /// into a <4 x float> that uses insert element.
251 /// 2) A fully general blob of memory, which we turn into some (potentially
252 /// large) integer type with extract and insert operations where the loads
253 /// and stores would mutate the memory. We mark this by setting VectorTy
255 void ConvertToScalarInfo::MergeInType(const Type *In, uint64_t Offset) {
256 // If we already decided to turn this into a blob of integer memory, there is
257 // nothing to be done.
258 if (VectorTy && VectorTy->isVoidTy())
261 // If this could be contributing to a vector, analyze it.
263 // If the In type is a vector that is the same size as the alloca, see if it
264 // matches the existing VecTy.
265 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
266 // Remember if we saw a vector type.
269 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
270 // If we're storing/loading a vector of the right size, allow it as a
271 // vector. If this the first vector we see, remember the type so that
272 // we know the element size. If this is a subsequent access, ignore it
273 // even if it is a differing type but the same size. Worst case we can
274 // bitcast the resultant vectors.
279 } else if (In->isFloatTy() || In->isDoubleTy() ||
280 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
281 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
282 // If we're accessing something that could be an element of a vector, see
283 // if the implied vector agrees with what we already have and if Offset is
284 // compatible with it.
285 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
286 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
288 cast<VectorType>(VectorTy)->getElementType()
289 ->getPrimitiveSizeInBits()/8 == EltSize)) {
291 VectorTy = VectorType::get(In, AllocaSize/EltSize);
296 // Otherwise, we have a case that we can't handle with an optimized vector
297 // form. We can still turn this into a large integer.
298 VectorTy = Type::getVoidTy(In->getContext());
301 /// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
302 /// its accesses to a single vector type, return true and set VecTy to
303 /// the new type. If we could convert the alloca into a single promotable
304 /// integer, return true but set VecTy to VoidTy. Further, if the use is not a
305 /// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
306 /// is the current offset from the base of the alloca being analyzed.
308 /// If we see at least one access to the value that is as a vector type, set the
310 bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
311 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
312 Instruction *User = cast<Instruction>(*UI);
314 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
315 // Don't break volatile loads.
316 if (LI->isVolatile())
318 MergeInType(LI->getType(), Offset);
322 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
323 // Storing the pointer, not into the value?
324 if (SI->getOperand(0) == V || SI->isVolatile()) return false;
325 MergeInType(SI->getOperand(0)->getType(), Offset);
329 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
330 IsNotTrivial = true; // Can't be mem2reg'd.
331 if (!CanConvertToScalar(BCI, Offset))
336 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
337 // If this is a GEP with a variable indices, we can't handle it.
338 if (!GEP->hasAllConstantIndices())
341 // Compute the offset that this GEP adds to the pointer.
342 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
343 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
344 &Indices[0], Indices.size());
345 // See if all uses can be converted.
346 if (!CanConvertToScalar(GEP, Offset+GEPOffset))
348 IsNotTrivial = true; // Can't be mem2reg'd.
352 // If this is a constant sized memset of a constant value (e.g. 0) we can
354 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
355 // Store of constant value and constant size.
356 if (!isa<ConstantInt>(MSI->getValue()) ||
357 !isa<ConstantInt>(MSI->getLength()))
359 IsNotTrivial = true; // Can't be mem2reg'd.
363 // If this is a memcpy or memmove into or out of the whole allocation, we
364 // can handle it like a load or store of the scalar type.
365 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
366 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
367 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
370 IsNotTrivial = true; // Can't be mem2reg'd.
374 // Otherwise, we cannot handle this!
381 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
382 /// directly. This happens when we are converting an "integer union" to a
383 /// single integer scalar, or when we are converting a "vector union" to a
384 /// vector with insert/extractelement instructions.
386 /// Offset is an offset from the original alloca, in bits that need to be
387 /// shifted to the right. By the end of this, there should be no uses of Ptr.
388 void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
390 while (!Ptr->use_empty()) {
391 Instruction *User = cast<Instruction>(Ptr->use_back());
393 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
394 ConvertUsesToScalar(CI, NewAI, Offset);
395 CI->eraseFromParent();
399 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
400 // Compute the offset that this GEP adds to the pointer.
401 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
402 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
403 &Indices[0], Indices.size());
404 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
405 GEP->eraseFromParent();
409 IRBuilder<> Builder(User->getParent(), User);
411 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
412 // The load is a bit extract from NewAI shifted right by Offset bits.
413 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
415 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
416 LI->replaceAllUsesWith(NewLoadVal);
417 LI->eraseFromParent();
421 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
422 assert(SI->getOperand(0) != Ptr && "Consistency error!");
423 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
424 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
426 Builder.CreateStore(New, NewAI);
427 SI->eraseFromParent();
429 // If the load we just inserted is now dead, then the inserted store
430 // overwrote the entire thing.
431 if (Old->use_empty())
432 Old->eraseFromParent();
436 // If this is a constant sized memset of a constant value (e.g. 0) we can
437 // transform it into a store of the expanded constant value.
438 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
439 assert(MSI->getRawDest() == Ptr && "Consistency error!");
440 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
442 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
444 // Compute the value replicated the right number of times.
445 APInt APVal(NumBytes*8, Val);
447 // Splat the value if non-zero.
449 for (unsigned i = 1; i != NumBytes; ++i)
452 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
453 Value *New = ConvertScalar_InsertValue(
454 ConstantInt::get(User->getContext(), APVal),
455 Old, Offset, Builder);
456 Builder.CreateStore(New, NewAI);
458 // If the load we just inserted is now dead, then the memset overwrote
460 if (Old->use_empty())
461 Old->eraseFromParent();
463 MSI->eraseFromParent();
467 // If this is a memcpy or memmove into or out of the whole allocation, we
468 // can handle it like a load or store of the scalar type.
469 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
470 assert(Offset == 0 && "must be store to start of alloca");
472 // If the source and destination are both to the same alloca, then this is
473 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
475 AllocaInst *OrigAI = cast<AllocaInst>(Ptr->getUnderlyingObject(0));
477 if (MTI->getSource()->getUnderlyingObject(0) != OrigAI) {
478 // Dest must be OrigAI, change this to be a load from the original
479 // pointer (bitcasted), then a store to our new alloca.
480 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
481 Value *SrcPtr = MTI->getSource();
482 SrcPtr = Builder.CreateBitCast(SrcPtr, NewAI->getType());
484 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
485 SrcVal->setAlignment(MTI->getAlignment());
486 Builder.CreateStore(SrcVal, NewAI);
487 } else if (MTI->getDest()->getUnderlyingObject(0) != OrigAI) {
488 // Src must be OrigAI, change this to be a load from NewAI then a store
489 // through the original dest pointer (bitcasted).
490 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
491 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
493 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), NewAI->getType());
494 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
495 NewStore->setAlignment(MTI->getAlignment());
497 // Noop transfer. Src == Dst
500 MTI->eraseFromParent();
504 llvm_unreachable("Unsupported operation!");
508 /// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
509 /// or vector value FromVal, extracting the bits from the offset specified by
510 /// Offset. This returns the value, which is of type ToType.
512 /// This happens when we are converting an "integer union" to a single
513 /// integer scalar, or when we are converting a "vector union" to a vector with
514 /// insert/extractelement instructions.
516 /// Offset is an offset from the original alloca, in bits that need to be
517 /// shifted to the right.
518 Value *ConvertToScalarInfo::
519 ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
520 uint64_t Offset, IRBuilder<> &Builder) {
521 // If the load is of the whole new alloca, no conversion is needed.
522 if (FromVal->getType() == ToType && Offset == 0)
525 // If the result alloca is a vector type, this is either an element
526 // access or a bitcast to another vector type of the same size.
527 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
528 if (ToType->isVectorTy())
529 return Builder.CreateBitCast(FromVal, ToType, "tmp");
531 // Otherwise it must be an element access.
534 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
535 Elt = Offset/EltSize;
536 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
538 // Return the element extracted out of it.
539 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
540 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
541 if (V->getType() != ToType)
542 V = Builder.CreateBitCast(V, ToType, "tmp");
546 // If ToType is a first class aggregate, extract out each of the pieces and
547 // use insertvalue's to form the FCA.
548 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
549 const StructLayout &Layout = *TD.getStructLayout(ST);
550 Value *Res = UndefValue::get(ST);
551 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
552 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
553 Offset+Layout.getElementOffsetInBits(i),
555 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
560 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
561 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
562 Value *Res = UndefValue::get(AT);
563 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
564 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
565 Offset+i*EltSize, Builder);
566 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
571 // Otherwise, this must be a union that was converted to an integer value.
572 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
574 // If this is a big-endian system and the load is narrower than the
575 // full alloca type, we need to do a shift to get the right bits.
577 if (TD.isBigEndian()) {
578 // On big-endian machines, the lowest bit is stored at the bit offset
579 // from the pointer given by getTypeStoreSizeInBits. This matters for
580 // integers with a bitwidth that is not a multiple of 8.
581 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
582 TD.getTypeStoreSizeInBits(ToType) - Offset;
587 // Note: we support negative bitwidths (with shl) which are not defined.
588 // We do this to support (f.e.) loads off the end of a structure where
589 // only some bits are used.
590 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
591 FromVal = Builder.CreateLShr(FromVal,
592 ConstantInt::get(FromVal->getType(),
594 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
595 FromVal = Builder.CreateShl(FromVal,
596 ConstantInt::get(FromVal->getType(),
599 // Finally, unconditionally truncate the integer to the right width.
600 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
601 if (LIBitWidth < NTy->getBitWidth())
603 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
605 else if (LIBitWidth > NTy->getBitWidth())
607 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
610 // If the result is an integer, this is a trunc or bitcast.
611 if (ToType->isIntegerTy()) {
613 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
614 // Just do a bitcast, we know the sizes match up.
615 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
617 // Otherwise must be a pointer.
618 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
620 assert(FromVal->getType() == ToType && "Didn't convert right?");
624 /// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
625 /// or vector value "Old" at the offset specified by Offset.
627 /// This happens when we are converting an "integer union" to a
628 /// single integer scalar, or when we are converting a "vector union" to a
629 /// vector with insert/extractelement instructions.
631 /// Offset is an offset from the original alloca, in bits that need to be
632 /// shifted to the right.
633 Value *ConvertToScalarInfo::
634 ConvertScalar_InsertValue(Value *SV, Value *Old,
635 uint64_t Offset, IRBuilder<> &Builder) {
636 // Convert the stored type to the actual type, shift it left to insert
637 // then 'or' into place.
638 const Type *AllocaType = Old->getType();
639 LLVMContext &Context = Old->getContext();
641 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
642 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
643 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
645 // Changing the whole vector with memset or with an access of a different
647 if (ValSize == VecSize)
648 return Builder.CreateBitCast(SV, AllocaType, "tmp");
650 uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
652 // Must be an element insertion.
653 unsigned Elt = Offset/EltSize;
655 if (SV->getType() != VTy->getElementType())
656 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
658 SV = Builder.CreateInsertElement(Old, SV,
659 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
664 // If SV is a first-class aggregate value, insert each value recursively.
665 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
666 const StructLayout &Layout = *TD.getStructLayout(ST);
667 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
668 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
669 Old = ConvertScalar_InsertValue(Elt, Old,
670 Offset+Layout.getElementOffsetInBits(i),
676 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
677 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
678 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
679 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
680 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
685 // If SV is a float, convert it to the appropriate integer type.
686 // If it is a pointer, do the same.
687 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
688 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
689 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
690 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
691 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
692 SV = Builder.CreateBitCast(SV,
693 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
694 else if (SV->getType()->isPointerTy())
695 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
697 // Zero extend or truncate the value if needed.
698 if (SV->getType() != AllocaType) {
699 if (SV->getType()->getPrimitiveSizeInBits() <
700 AllocaType->getPrimitiveSizeInBits())
701 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
703 // Truncation may be needed if storing more than the alloca can hold
704 // (undefined behavior).
705 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
706 SrcWidth = DestWidth;
707 SrcStoreWidth = DestStoreWidth;
711 // If this is a big-endian system and the store is narrower than the
712 // full alloca type, we need to do a shift to get the right bits.
714 if (TD.isBigEndian()) {
715 // On big-endian machines, the lowest bit is stored at the bit offset
716 // from the pointer given by getTypeStoreSizeInBits. This matters for
717 // integers with a bitwidth that is not a multiple of 8.
718 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
723 // Note: we support negative bitwidths (with shr) which are not defined.
724 // We do this to support (f.e.) stores off the end of a structure where
725 // only some bits in the structure are set.
726 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
727 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
728 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
731 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
732 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
734 Mask = Mask.lshr(-ShAmt);
737 // Mask out the bits we are about to insert from the old value, and or
739 if (SrcWidth != DestWidth) {
740 assert(DestWidth > SrcWidth);
741 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
742 SV = Builder.CreateOr(Old, SV, "ins");
748 //===----------------------------------------------------------------------===//
750 //===----------------------------------------------------------------------===//
753 bool SROA::runOnFunction(Function &F) {
754 TD = getAnalysisIfAvailable<TargetData>();
756 bool Changed = performPromotion(F);
758 // FIXME: ScalarRepl currently depends on TargetData more than it
759 // theoretically needs to. It should be refactored in order to support
760 // target-independent IR. Until this is done, just skip the actual
761 // scalar-replacement portion of this pass.
762 if (!TD) return Changed;
765 bool LocalChange = performScalarRepl(F);
766 if (!LocalChange) break; // No need to repromote if no scalarrepl
768 LocalChange = performPromotion(F);
769 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
776 bool SROA::performPromotion(Function &F) {
777 std::vector<AllocaInst*> Allocas;
778 DominatorTree &DT = getAnalysis<DominatorTree>();
779 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
781 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
783 bool Changed = false;
788 // Find allocas that are safe to promote, by looking at all instructions in
790 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
791 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
792 if (isAllocaPromotable(AI))
793 Allocas.push_back(AI);
795 if (Allocas.empty()) break;
797 PromoteMemToReg(Allocas, DT, DF);
798 NumPromoted += Allocas.size();
806 /// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
807 /// SROA. It must be a struct or array type with a small number of elements.
808 static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
809 const Type *T = AI->getAllocatedType();
810 // Do not promote any struct into more than 32 separate vars.
811 if (const StructType *ST = dyn_cast<StructType>(T))
812 return ST->getNumElements() <= 32;
813 // Arrays are much less likely to be safe for SROA; only consider
814 // them if they are very small.
815 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
816 return AT->getNumElements() <= 8;
821 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
822 // which runs on all of the malloc/alloca instructions in the function, removing
823 // them if they are only used by getelementptr instructions.
825 bool SROA::performScalarRepl(Function &F) {
826 std::vector<AllocaInst*> WorkList;
828 // Scan the entry basic block, adding allocas to the worklist.
829 BasicBlock &BB = F.getEntryBlock();
830 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
831 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
832 WorkList.push_back(A);
834 // Process the worklist
835 bool Changed = false;
836 while (!WorkList.empty()) {
837 AllocaInst *AI = WorkList.back();
840 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
841 // with unused elements.
842 if (AI->use_empty()) {
843 AI->eraseFromParent();
848 // If this alloca is impossible for us to promote, reject it early.
849 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
852 // Check to see if this allocation is only modified by a memcpy/memmove from
853 // a constant global. If this is the case, we can change all users to use
854 // the constant global instead. This is commonly produced by the CFE by
855 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
856 // is only subsequently read.
857 if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
858 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
859 DEBUG(dbgs() << " memcpy = " << *TheCopy << '\n');
860 Constant *TheSrc = cast<Constant>(TheCopy->getSource());
861 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
862 TheCopy->eraseFromParent(); // Don't mutate the global.
863 AI->eraseFromParent();
869 // Check to see if we can perform the core SROA transformation. We cannot
870 // transform the allocation instruction if it is an array allocation
871 // (allocations OF arrays are ok though), and an allocation of a scalar
872 // value cannot be decomposed at all.
873 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
875 // Do not promote [0 x %struct].
876 if (AllocaSize == 0) continue;
878 // Do not promote any struct whose size is too big.
879 if (AllocaSize > SRThreshold) continue;
881 // If the alloca looks like a good candidate for scalar replacement, and if
882 // all its users can be transformed, then split up the aggregate into its
883 // separate elements.
884 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
885 DoScalarReplacement(AI, WorkList);
890 // If we can turn this aggregate value (potentially with casts) into a
891 // simple scalar value that can be mem2reg'd into a register value.
892 // IsNotTrivial tracks whether this is something that mem2reg could have
893 // promoted itself. If so, we don't want to transform it needlessly. Note
894 // that we can't just check based on the type: the alloca may be of an i32
895 // but that has pointer arithmetic to set byte 3 of it or something.
896 if (AllocaInst *NewAI =
897 ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
899 AI->eraseFromParent();
905 // Otherwise, couldn't process this alloca.
911 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
912 /// predicate, do SROA now.
913 void SROA::DoScalarReplacement(AllocaInst *AI,
914 std::vector<AllocaInst*> &WorkList) {
915 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
916 SmallVector<AllocaInst*, 32> ElementAllocas;
917 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
918 ElementAllocas.reserve(ST->getNumContainedTypes());
919 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
920 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
922 AI->getName() + "." + Twine(i), AI);
923 ElementAllocas.push_back(NA);
924 WorkList.push_back(NA); // Add to worklist for recursive processing
927 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
928 ElementAllocas.reserve(AT->getNumElements());
929 const Type *ElTy = AT->getElementType();
930 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
931 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
932 AI->getName() + "." + Twine(i), AI);
933 ElementAllocas.push_back(NA);
934 WorkList.push_back(NA); // Add to worklist for recursive processing
938 // Now that we have created the new alloca instructions, rewrite all the
939 // uses of the old alloca.
940 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
942 // Now erase any instructions that were made dead while rewriting the alloca.
943 DeleteDeadInstructions();
944 AI->eraseFromParent();
949 /// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
950 /// recursively including all their operands that become trivially dead.
951 void SROA::DeleteDeadInstructions() {
952 while (!DeadInsts.empty()) {
953 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
955 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
956 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
957 // Zero out the operand and see if it becomes trivially dead.
958 // (But, don't add allocas to the dead instruction list -- they are
959 // already on the worklist and will be deleted separately.)
961 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
962 DeadInsts.push_back(U);
965 I->eraseFromParent();
969 /// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
970 /// performing scalar replacement of alloca AI. The results are flagged in
971 /// the Info parameter. Offset indicates the position within AI that is
972 /// referenced by this instruction.
973 void SROA::isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
975 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
976 Instruction *User = cast<Instruction>(*UI);
978 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
979 isSafeForScalarRepl(BC, AI, Offset, Info);
980 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
981 uint64_t GEPOffset = Offset;
982 isSafeGEP(GEPI, AI, GEPOffset, Info);
984 isSafeForScalarRepl(GEPI, AI, GEPOffset, Info);
985 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
986 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
988 isSafeMemAccess(AI, Offset, Length->getZExtValue(), 0,
989 UI.getOperandNo() == 0, Info);
992 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
993 if (!LI->isVolatile()) {
994 const Type *LIType = LI->getType();
995 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(LIType),
996 LIType, false, Info);
999 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1000 // Store is ok if storing INTO the pointer, not storing the pointer
1001 if (!SI->isVolatile() && SI->getOperand(0) != I) {
1002 const Type *SIType = SI->getOperand(0)->getType();
1003 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(SIType),
1004 SIType, true, Info);
1008 DEBUG(errs() << " Transformation preventing inst: " << *User << '\n');
1011 if (Info.isUnsafe) return;
1015 /// isSafeGEP - Check if a GEP instruction can be handled for scalar
1016 /// replacement. It is safe when all the indices are constant, in-bounds
1017 /// references, and when the resulting offset corresponds to an element within
1018 /// the alloca type. The results are flagged in the Info parameter. Upon
1019 /// return, Offset is adjusted as specified by the GEP indices.
1020 void SROA::isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI,
1021 uint64_t &Offset, AllocaInfo &Info) {
1022 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1026 // Walk through the GEP type indices, checking the types that this indexes
1028 for (; GEPIt != E; ++GEPIt) {
1029 // Ignore struct elements, no extra checking needed for these.
1030 if ((*GEPIt)->isStructTy())
1033 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1035 return MarkUnsafe(Info);
1038 // Compute the offset due to this GEP and check if the alloca has a
1039 // component element at that offset.
1040 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1041 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1042 &Indices[0], Indices.size());
1043 if (!TypeHasComponent(AI->getAllocatedType(), Offset, 0))
1047 /// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1048 /// alloca or has an offset and size that corresponds to a component element
1049 /// within it. The offset checked here may have been formed from a GEP with a
1050 /// pointer bitcasted to a different type.
1051 void SROA::isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
1052 const Type *MemOpType, bool isStore,
1054 // Check if this is a load/store of the entire alloca.
1055 if (Offset == 0 && MemSize == TD->getTypeAllocSize(AI->getAllocatedType())) {
1056 bool UsesAggregateType = (MemOpType == AI->getAllocatedType());
1057 // This is safe for MemIntrinsics (where MemOpType is 0), integer types
1058 // (which are essentially the same as the MemIntrinsics, especially with
1059 // regard to copying padding between elements), or references using the
1060 // aggregate type of the alloca.
1061 if (!MemOpType || MemOpType->isIntegerTy() || UsesAggregateType) {
1062 if (!UsesAggregateType) {
1064 Info.isMemCpyDst = true;
1066 Info.isMemCpySrc = true;
1071 // Check if the offset/size correspond to a component within the alloca type.
1072 const Type *T = AI->getAllocatedType();
1073 if (TypeHasComponent(T, Offset, MemSize))
1076 return MarkUnsafe(Info);
1079 /// TypeHasComponent - Return true if T has a component type with the
1080 /// specified offset and size. If Size is zero, do not check the size.
1081 bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
1084 if (const StructType *ST = dyn_cast<StructType>(T)) {
1085 const StructLayout *Layout = TD->getStructLayout(ST);
1086 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1087 EltTy = ST->getContainedType(EltIdx);
1088 EltSize = TD->getTypeAllocSize(EltTy);
1089 Offset -= Layout->getElementOffset(EltIdx);
1090 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1091 EltTy = AT->getElementType();
1092 EltSize = TD->getTypeAllocSize(EltTy);
1093 if (Offset >= AT->getNumElements() * EltSize)
1099 if (Offset == 0 && (Size == 0 || EltSize == Size))
1101 // Check if the component spans multiple elements.
1102 if (Offset + Size > EltSize)
1104 return TypeHasComponent(EltTy, Offset, Size);
1107 /// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1108 /// the instruction I, which references it, to use the separate elements.
1109 /// Offset indicates the position within AI that is referenced by this
1111 void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1112 SmallVector<AllocaInst*, 32> &NewElts) {
1113 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1114 Instruction *User = cast<Instruction>(*UI);
1116 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1117 RewriteBitCast(BC, AI, Offset, NewElts);
1118 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1119 RewriteGEP(GEPI, AI, Offset, NewElts);
1120 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1121 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1122 uint64_t MemSize = Length->getZExtValue();
1124 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1125 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
1126 // Otherwise the intrinsic can only touch a single element and the
1127 // address operand will be updated, so nothing else needs to be done.
1128 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1129 const Type *LIType = LI->getType();
1130 if (LIType == AI->getAllocatedType()) {
1132 // %res = load { i32, i32 }* %alloc
1134 // %load.0 = load i32* %alloc.0
1135 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1136 // %load.1 = load i32* %alloc.1
1137 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1138 // (Also works for arrays instead of structs)
1139 Value *Insert = UndefValue::get(LIType);
1140 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1141 Value *Load = new LoadInst(NewElts[i], "load", LI);
1142 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
1144 LI->replaceAllUsesWith(Insert);
1145 DeadInsts.push_back(LI);
1146 } else if (LIType->isIntegerTy() &&
1147 TD->getTypeAllocSize(LIType) ==
1148 TD->getTypeAllocSize(AI->getAllocatedType())) {
1149 // If this is a load of the entire alloca to an integer, rewrite it.
1150 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1152 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1153 Value *Val = SI->getOperand(0);
1154 const Type *SIType = Val->getType();
1155 if (SIType == AI->getAllocatedType()) {
1157 // store { i32, i32 } %val, { i32, i32 }* %alloc
1159 // %val.0 = extractvalue { i32, i32 } %val, 0
1160 // store i32 %val.0, i32* %alloc.0
1161 // %val.1 = extractvalue { i32, i32 } %val, 1
1162 // store i32 %val.1, i32* %alloc.1
1163 // (Also works for arrays instead of structs)
1164 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1165 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
1166 new StoreInst(Extract, NewElts[i], SI);
1168 DeadInsts.push_back(SI);
1169 } else if (SIType->isIntegerTy() &&
1170 TD->getTypeAllocSize(SIType) ==
1171 TD->getTypeAllocSize(AI->getAllocatedType())) {
1172 // If this is a store of the entire alloca from an integer, rewrite it.
1173 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1179 /// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1180 /// and recursively continue updating all of its uses.
1181 void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1182 SmallVector<AllocaInst*, 32> &NewElts) {
1183 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1184 if (BC->getOperand(0) != AI)
1187 // The bitcast references the original alloca. Replace its uses with
1188 // references to the first new element alloca.
1189 Instruction *Val = NewElts[0];
1190 if (Val->getType() != BC->getDestTy()) {
1191 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1194 BC->replaceAllUsesWith(Val);
1195 DeadInsts.push_back(BC);
1198 /// FindElementAndOffset - Return the index of the element containing Offset
1199 /// within the specified type, which must be either a struct or an array.
1200 /// Sets T to the type of the element and Offset to the offset within that
1201 /// element. IdxTy is set to the type of the index result to be used in a
1202 /// GEP instruction.
1203 uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
1204 const Type *&IdxTy) {
1206 if (const StructType *ST = dyn_cast<StructType>(T)) {
1207 const StructLayout *Layout = TD->getStructLayout(ST);
1208 Idx = Layout->getElementContainingOffset(Offset);
1209 T = ST->getContainedType(Idx);
1210 Offset -= Layout->getElementOffset(Idx);
1211 IdxTy = Type::getInt32Ty(T->getContext());
1214 const ArrayType *AT = cast<ArrayType>(T);
1215 T = AT->getElementType();
1216 uint64_t EltSize = TD->getTypeAllocSize(T);
1217 Idx = Offset / EltSize;
1218 Offset -= Idx * EltSize;
1219 IdxTy = Type::getInt64Ty(T->getContext());
1223 /// RewriteGEP - Check if this GEP instruction moves the pointer across
1224 /// elements of the alloca that are being split apart, and if so, rewrite
1225 /// the GEP to be relative to the new element.
1226 void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1227 SmallVector<AllocaInst*, 32> &NewElts) {
1228 uint64_t OldOffset = Offset;
1229 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1230 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1231 &Indices[0], Indices.size());
1233 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1235 const Type *T = AI->getAllocatedType();
1237 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
1238 if (GEPI->getOperand(0) == AI)
1239 OldIdx = ~0ULL; // Force the GEP to be rewritten.
1241 T = AI->getAllocatedType();
1242 uint64_t EltOffset = Offset;
1243 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
1245 // If this GEP does not move the pointer across elements of the alloca
1246 // being split, then it does not needs to be rewritten.
1250 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
1251 SmallVector<Value*, 8> NewArgs;
1252 NewArgs.push_back(Constant::getNullValue(i32Ty));
1253 while (EltOffset != 0) {
1254 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
1255 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
1257 Instruction *Val = NewElts[Idx];
1258 if (NewArgs.size() > 1) {
1259 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
1260 NewArgs.end(), "", GEPI);
1261 Val->takeName(GEPI);
1263 if (Val->getType() != GEPI->getType())
1264 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
1265 GEPI->replaceAllUsesWith(Val);
1266 DeadInsts.push_back(GEPI);
1269 /// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
1270 /// Rewrite it to copy or set the elements of the scalarized memory.
1271 void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
1273 SmallVector<AllocaInst*, 32> &NewElts) {
1274 // If this is a memcpy/memmove, construct the other pointer as the
1275 // appropriate type. The "Other" pointer is the pointer that goes to memory
1276 // that doesn't have anything to do with the alloca that we are promoting. For
1277 // memset, this Value* stays null.
1278 Value *OtherPtr = 0;
1279 unsigned MemAlignment = MI->getAlignment();
1280 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
1281 if (Inst == MTI->getRawDest())
1282 OtherPtr = MTI->getRawSource();
1284 assert(Inst == MTI->getRawSource());
1285 OtherPtr = MTI->getRawDest();
1289 // If there is an other pointer, we want to convert it to the same pointer
1290 // type as AI has, so we can GEP through it safely.
1292 unsigned AddrSpace =
1293 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
1295 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
1296 // optimization, but it's also required to detect the corner case where
1297 // both pointer operands are referencing the same memory, and where
1298 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
1299 // function is only called for mem intrinsics that access the whole
1300 // aggregate, so non-zero GEPs are not an issue here.)
1301 OtherPtr = OtherPtr->stripPointerCasts();
1303 // Copying the alloca to itself is a no-op: just delete it.
1304 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
1305 // This code will run twice for a no-op memcpy -- once for each operand.
1306 // Put only one reference to MI on the DeadInsts list.
1307 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
1308 E = DeadInsts.end(); I != E; ++I)
1309 if (*I == MI) return;
1310 DeadInsts.push_back(MI);
1314 // If the pointer is not the right type, insert a bitcast to the right
1317 PointerType::get(AI->getType()->getElementType(), AddrSpace);
1319 if (OtherPtr->getType() != NewTy)
1320 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
1323 // Process each element of the aggregate.
1324 Value *TheFn = MI->getCalledValue();
1325 const Type *BytePtrTy = MI->getRawDest()->getType();
1326 bool SROADest = MI->getRawDest() == Inst;
1328 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
1330 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1331 // If this is a memcpy/memmove, emit a GEP of the other element address.
1332 Value *OtherElt = 0;
1333 unsigned OtherEltAlign = MemAlignment;
1336 Value *Idx[2] = { Zero,
1337 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
1338 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
1339 OtherPtr->getName()+"."+Twine(i),
1342 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
1343 const Type *OtherTy = OtherPtrTy->getElementType();
1344 if (const StructType *ST = dyn_cast<StructType>(OtherTy)) {
1345 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
1347 const Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
1348 EltOffset = TD->getTypeAllocSize(EltTy)*i;
1351 // The alignment of the other pointer is the guaranteed alignment of the
1352 // element, which is affected by both the known alignment of the whole
1353 // mem intrinsic and the alignment of the element. If the alignment of
1354 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
1355 // known alignment is just 4 bytes.
1356 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
1359 Value *EltPtr = NewElts[i];
1360 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
1362 // If we got down to a scalar, insert a load or store as appropriate.
1363 if (EltTy->isSingleValueType()) {
1364 if (isa<MemTransferInst>(MI)) {
1366 // From Other to Alloca.
1367 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
1368 new StoreInst(Elt, EltPtr, MI);
1370 // From Alloca to Other.
1371 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
1372 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
1376 assert(isa<MemSetInst>(MI));
1378 // If the stored element is zero (common case), just store a null
1381 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
1383 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
1385 // If EltTy is a vector type, get the element type.
1386 const Type *ValTy = EltTy->getScalarType();
1388 // Construct an integer with the right value.
1389 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
1390 APInt OneVal(EltSize, CI->getZExtValue());
1391 APInt TotalVal(OneVal);
1393 for (unsigned i = 0; 8*i < EltSize; ++i) {
1394 TotalVal = TotalVal.shl(8);
1398 // Convert the integer value to the appropriate type.
1399 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
1400 if (ValTy->isPointerTy())
1401 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
1402 else if (ValTy->isFloatingPointTy())
1403 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
1404 assert(StoreVal->getType() == ValTy && "Type mismatch!");
1406 // If the requested value was a vector constant, create it.
1407 if (EltTy != ValTy) {
1408 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
1409 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
1410 StoreVal = ConstantVector::get(&Elts[0], NumElts);
1413 new StoreInst(StoreVal, EltPtr, MI);
1416 // Otherwise, if we're storing a byte variable, use a memset call for
1420 // Cast the element pointer to BytePtrTy.
1421 if (EltPtr->getType() != BytePtrTy)
1422 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getName(), MI);
1424 // Cast the other pointer (if we have one) to BytePtrTy.
1425 if (OtherElt && OtherElt->getType() != BytePtrTy) {
1426 // Preserve address space of OtherElt
1427 const PointerType* OtherPTy = cast<PointerType>(OtherElt->getType());
1428 const PointerType* PTy = cast<PointerType>(BytePtrTy);
1429 if (OtherPTy->getElementType() != PTy->getElementType()) {
1430 Type *NewOtherPTy = PointerType::get(PTy->getElementType(),
1431 OtherPTy->getAddressSpace());
1432 OtherElt = new BitCastInst(OtherElt, NewOtherPTy,
1433 OtherElt->getNameStr(), MI);
1437 unsigned EltSize = TD->getTypeAllocSize(EltTy);
1439 // Finally, insert the meminst for this element.
1440 if (isa<MemTransferInst>(MI)) {
1442 SROADest ? EltPtr : OtherElt, // Dest ptr
1443 SROADest ? OtherElt : EltPtr, // Src ptr
1444 ConstantInt::get(MI->getArgOperand(2)->getType(), EltSize), // Size
1446 ConstantInt::get(Type::getInt32Ty(MI->getContext()), OtherEltAlign),
1447 MI->getVolatileCst()
1449 // In case we fold the address space overloaded memcpy of A to B
1450 // with memcpy of B to C, change the function to be a memcpy of A to C.
1451 const Type *Tys[] = { Ops[0]->getType(), Ops[1]->getType(),
1452 Ops[2]->getType() };
1453 Module *M = MI->getParent()->getParent()->getParent();
1454 TheFn = Intrinsic::getDeclaration(M, MI->getIntrinsicID(), Tys, 3);
1455 CallInst::Create(TheFn, Ops, Ops + 5, "", MI);
1457 assert(isa<MemSetInst>(MI));
1459 EltPtr, MI->getArgOperand(1), // Dest, Value,
1460 ConstantInt::get(MI->getArgOperand(2)->getType(), EltSize), // Size
1462 ConstantInt::get(Type::getInt1Ty(MI->getContext()), 0) // isVolatile
1464 const Type *Tys[] = { Ops[0]->getType(), Ops[2]->getType() };
1465 Module *M = MI->getParent()->getParent()->getParent();
1466 TheFn = Intrinsic::getDeclaration(M, Intrinsic::memset, Tys, 2);
1467 CallInst::Create(TheFn, Ops, Ops + 5, "", MI);
1470 DeadInsts.push_back(MI);
1473 /// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
1474 /// overwrites the entire allocation. Extract out the pieces of the stored
1475 /// integer and store them individually.
1476 void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
1477 SmallVector<AllocaInst*, 32> &NewElts){
1478 // Extract each element out of the integer according to its structure offset
1479 // and store the element value to the individual alloca.
1480 Value *SrcVal = SI->getOperand(0);
1481 const Type *AllocaEltTy = AI->getAllocatedType();
1482 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
1484 // Handle tail padding by extending the operand
1485 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
1486 SrcVal = new ZExtInst(SrcVal,
1487 IntegerType::get(SI->getContext(), AllocaSizeBits),
1490 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
1493 // There are two forms here: AI could be an array or struct. Both cases
1494 // have different ways to compute the element offset.
1495 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1496 const StructLayout *Layout = TD->getStructLayout(EltSTy);
1498 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1499 // Get the number of bits to shift SrcVal to get the value.
1500 const Type *FieldTy = EltSTy->getElementType(i);
1501 uint64_t Shift = Layout->getElementOffsetInBits(i);
1503 if (TD->isBigEndian())
1504 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
1506 Value *EltVal = SrcVal;
1508 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
1509 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1510 "sroa.store.elt", SI);
1513 // Truncate down to an integer of the right size.
1514 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1516 // Ignore zero sized fields like {}, they obviously contain no data.
1517 if (FieldSizeBits == 0) continue;
1519 if (FieldSizeBits != AllocaSizeBits)
1520 EltVal = new TruncInst(EltVal,
1521 IntegerType::get(SI->getContext(), FieldSizeBits),
1523 Value *DestField = NewElts[i];
1524 if (EltVal->getType() == FieldTy) {
1525 // Storing to an integer field of this size, just do it.
1526 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
1527 // Bitcast to the right element type (for fp/vector values).
1528 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
1530 // Otherwise, bitcast the dest pointer (for aggregates).
1531 DestField = new BitCastInst(DestField,
1532 PointerType::getUnqual(EltVal->getType()),
1535 new StoreInst(EltVal, DestField, SI);
1539 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
1540 const Type *ArrayEltTy = ATy->getElementType();
1541 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
1542 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
1546 if (TD->isBigEndian())
1547 Shift = AllocaSizeBits-ElementOffset;
1551 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1552 // Ignore zero sized fields like {}, they obviously contain no data.
1553 if (ElementSizeBits == 0) continue;
1555 Value *EltVal = SrcVal;
1557 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
1558 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1559 "sroa.store.elt", SI);
1562 // Truncate down to an integer of the right size.
1563 if (ElementSizeBits != AllocaSizeBits)
1564 EltVal = new TruncInst(EltVal,
1565 IntegerType::get(SI->getContext(),
1566 ElementSizeBits),"",SI);
1567 Value *DestField = NewElts[i];
1568 if (EltVal->getType() == ArrayEltTy) {
1569 // Storing to an integer field of this size, just do it.
1570 } else if (ArrayEltTy->isFloatingPointTy() ||
1571 ArrayEltTy->isVectorTy()) {
1572 // Bitcast to the right element type (for fp/vector values).
1573 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
1575 // Otherwise, bitcast the dest pointer (for aggregates).
1576 DestField = new BitCastInst(DestField,
1577 PointerType::getUnqual(EltVal->getType()),
1580 new StoreInst(EltVal, DestField, SI);
1582 if (TD->isBigEndian())
1583 Shift -= ElementOffset;
1585 Shift += ElementOffset;
1589 DeadInsts.push_back(SI);
1592 /// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
1593 /// an integer. Load the individual pieces to form the aggregate value.
1594 void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
1595 SmallVector<AllocaInst*, 32> &NewElts) {
1596 // Extract each element out of the NewElts according to its structure offset
1597 // and form the result value.
1598 const Type *AllocaEltTy = AI->getAllocatedType();
1599 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
1601 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
1604 // There are two forms here: AI could be an array or struct. Both cases
1605 // have different ways to compute the element offset.
1606 const StructLayout *Layout = 0;
1607 uint64_t ArrayEltBitOffset = 0;
1608 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1609 Layout = TD->getStructLayout(EltSTy);
1611 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
1612 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
1616 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
1618 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1619 // Load the value from the alloca. If the NewElt is an aggregate, cast
1620 // the pointer to an integer of the same size before doing the load.
1621 Value *SrcField = NewElts[i];
1622 const Type *FieldTy =
1623 cast<PointerType>(SrcField->getType())->getElementType();
1624 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1626 // Ignore zero sized fields like {}, they obviously contain no data.
1627 if (FieldSizeBits == 0) continue;
1629 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
1631 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
1632 !FieldTy->isVectorTy())
1633 SrcField = new BitCastInst(SrcField,
1634 PointerType::getUnqual(FieldIntTy),
1636 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1638 // If SrcField is a fp or vector of the right size but that isn't an
1639 // integer type, bitcast to an integer so we can shift it.
1640 if (SrcField->getType() != FieldIntTy)
1641 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1643 // Zero extend the field to be the same size as the final alloca so that
1644 // we can shift and insert it.
1645 if (SrcField->getType() != ResultVal->getType())
1646 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1648 // Determine the number of bits to shift SrcField.
1650 if (Layout) // Struct case.
1651 Shift = Layout->getElementOffsetInBits(i);
1653 Shift = i*ArrayEltBitOffset;
1655 if (TD->isBigEndian())
1656 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1659 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
1660 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1663 // Don't create an 'or x, 0' on the first iteration.
1664 if (!isa<Constant>(ResultVal) ||
1665 !cast<Constant>(ResultVal)->isNullValue())
1666 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1668 ResultVal = SrcField;
1671 // Handle tail padding by truncating the result
1672 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1673 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1675 LI->replaceAllUsesWith(ResultVal);
1676 DeadInsts.push_back(LI);
1679 /// HasPadding - Return true if the specified type has any structure or
1680 /// alignment padding, false otherwise.
1681 static bool HasPadding(const Type *Ty, const TargetData &TD) {
1682 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty))
1683 return HasPadding(ATy->getElementType(), TD);
1685 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
1686 return HasPadding(VTy->getElementType(), TD);
1688 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1689 const StructLayout *SL = TD.getStructLayout(STy);
1690 unsigned PrevFieldBitOffset = 0;
1691 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1692 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1694 // Padding in sub-elements?
1695 if (HasPadding(STy->getElementType(i), TD))
1698 // Check to see if there is any padding between this element and the
1701 unsigned PrevFieldEnd =
1702 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1703 if (PrevFieldEnd < FieldBitOffset)
1707 PrevFieldBitOffset = FieldBitOffset;
1710 // Check for tail padding.
1711 if (unsigned EltCount = STy->getNumElements()) {
1712 unsigned PrevFieldEnd = PrevFieldBitOffset +
1713 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
1714 if (PrevFieldEnd < SL->getSizeInBits())
1719 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
1722 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1723 /// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1724 /// or 1 if safe after canonicalization has been performed.
1725 bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
1726 // Loop over the use list of the alloca. We can only transform it if all of
1727 // the users are safe to transform.
1730 isSafeForScalarRepl(AI, AI, 0, Info);
1731 if (Info.isUnsafe) {
1732 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
1736 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1737 // source and destination, we have to be careful. In particular, the memcpy
1738 // could be moving around elements that live in structure padding of the LLVM
1739 // types, but may actually be used. In these cases, we refuse to promote the
1741 if (Info.isMemCpySrc && Info.isMemCpyDst &&
1742 HasPadding(AI->getAllocatedType(), *TD))
1750 /// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1751 /// some part of a constant global variable. This intentionally only accepts
1752 /// constant expressions because we don't can't rewrite arbitrary instructions.
1753 static bool PointsToConstantGlobal(Value *V) {
1754 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1755 return GV->isConstant();
1756 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1757 if (CE->getOpcode() == Instruction::BitCast ||
1758 CE->getOpcode() == Instruction::GetElementPtr)
1759 return PointsToConstantGlobal(CE->getOperand(0));
1763 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1764 /// pointer to an alloca. Ignore any reads of the pointer, return false if we
1765 /// see any stores or other unknown uses. If we see pointer arithmetic, keep
1766 /// track of whether it moves the pointer (with isOffset) but otherwise traverse
1767 /// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1768 /// the alloca, and if the source pointer is a pointer to a constant global, we
1769 /// can optimize this.
1770 static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
1772 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1773 User *U = cast<Instruction>(*UI);
1775 if (LoadInst *LI = dyn_cast<LoadInst>(U))
1776 // Ignore non-volatile loads, they are always ok.
1777 if (!LI->isVolatile())
1780 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
1781 // If uses of the bitcast are ok, we are ok.
1782 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1786 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
1787 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1788 // doesn't, it does.
1789 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1790 isOffset || !GEP->hasAllZeroIndices()))
1795 // If this is isn't our memcpy/memmove, reject it as something we can't
1797 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
1801 // If we already have seen a copy, reject the second one.
1802 if (TheCopy) return false;
1804 // If the pointer has been offset from the start of the alloca, we can't
1805 // safely handle this.
1806 if (isOffset) return false;
1808 // If the memintrinsic isn't using the alloca as the dest, reject it.
1809 if (UI.getOperandNo() != 0) return false;
1811 // If the source of the memcpy/move is not a constant global, reject it.
1812 if (!PointsToConstantGlobal(MI->getSource()))
1815 // Otherwise, the transform is safe. Remember the copy instruction.
1821 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1822 /// modified by a copy from a constant global. If we can prove this, we can
1823 /// replace any uses of the alloca with uses of the global directly.
1824 MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
1825 MemTransferInst *TheCopy = 0;
1826 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))