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/Pass.h"
31 #include "llvm/Analysis/Dominators.h"
32 #include "llvm/Target/TargetData.h"
33 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
34 #include "llvm/Transforms/Utils/Local.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/GetElementPtrTypeIterator.h"
37 #include "llvm/Support/IRBuilder.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/Compiler.h"
40 #include "llvm/ADT/SmallVector.h"
41 #include "llvm/ADT/Statistic.h"
42 #include "llvm/ADT/StringExtras.h"
45 STATISTIC(NumReplaced, "Number of allocas broken up");
46 STATISTIC(NumPromoted, "Number of allocas promoted");
47 STATISTIC(NumConverted, "Number of aggregates converted to scalar");
48 STATISTIC(NumGlobals, "Number of allocas copied from constant global");
51 struct VISIBILITY_HIDDEN SROA : public FunctionPass {
52 static char ID; // Pass identification, replacement for typeid
53 explicit SROA(signed T = -1) : FunctionPass(&ID) {
60 bool runOnFunction(Function &F);
62 bool performScalarRepl(Function &F);
63 bool performPromotion(Function &F);
65 // getAnalysisUsage - This pass does not require any passes, but we know it
66 // will not alter the CFG, so say so.
67 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
68 AU.addRequired<DominatorTree>();
69 AU.addRequired<DominanceFrontier>();
70 AU.addRequired<TargetData>();
77 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
78 /// information about the uses. All these fields are initialized to false
79 /// and set to true when something is learned.
81 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
84 /// needsCleanup - This is set to true if there is some use of the alloca
85 /// that requires cleanup.
86 bool needsCleanup : 1;
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), needsCleanup(false),
96 isMemCpySrc(false), isMemCpyDst(false) {}
101 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
103 int isSafeAllocaToScalarRepl(AllocationInst *AI);
105 void isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
107 void isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
109 void isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
110 unsigned OpNo, AllocaInfo &Info);
111 void isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI,
114 void DoScalarReplacement(AllocationInst *AI,
115 std::vector<AllocationInst*> &WorkList);
116 void CleanupGEP(GetElementPtrInst *GEP);
117 void CleanupAllocaUsers(AllocationInst *AI);
118 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
120 void RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
121 SmallVector<AllocaInst*, 32> &NewElts);
123 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
125 SmallVector<AllocaInst*, 32> &NewElts);
126 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocationInst *AI,
127 SmallVector<AllocaInst*, 32> &NewElts);
128 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
129 SmallVector<AllocaInst*, 32> &NewElts);
131 bool CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
132 bool &SawVec, uint64_t Offset, unsigned AllocaSize);
133 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
134 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
135 uint64_t Offset, IRBuilder<> &Builder);
136 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
137 uint64_t Offset, IRBuilder<> &Builder);
138 static Instruction *isOnlyCopiedFromConstantGlobal(AllocationInst *AI);
143 static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
145 // Public interface to the ScalarReplAggregates pass
146 FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
147 return new SROA(Threshold);
151 bool SROA::runOnFunction(Function &F) {
152 TD = &getAnalysis<TargetData>();
154 bool Changed = performPromotion(F);
156 bool LocalChange = performScalarRepl(F);
157 if (!LocalChange) break; // No need to repromote if no scalarrepl
159 LocalChange = performPromotion(F);
160 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
167 bool SROA::performPromotion(Function &F) {
168 std::vector<AllocaInst*> Allocas;
169 DominatorTree &DT = getAnalysis<DominatorTree>();
170 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
172 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
174 bool Changed = false;
179 // Find allocas that are safe to promote, by looking at all instructions in
181 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
182 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
183 if (isAllocaPromotable(AI))
184 Allocas.push_back(AI);
186 if (Allocas.empty()) break;
188 PromoteMemToReg(Allocas, DT, DF);
189 NumPromoted += Allocas.size();
196 /// getNumSAElements - Return the number of elements in the specific struct or
198 static uint64_t getNumSAElements(const Type *T) {
199 if (const StructType *ST = dyn_cast<StructType>(T))
200 return ST->getNumElements();
201 return cast<ArrayType>(T)->getNumElements();
204 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
205 // which runs on all of the malloc/alloca instructions in the function, removing
206 // them if they are only used by getelementptr instructions.
208 bool SROA::performScalarRepl(Function &F) {
209 std::vector<AllocationInst*> WorkList;
211 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
212 BasicBlock &BB = F.getEntryBlock();
213 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
214 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
215 WorkList.push_back(A);
217 // Process the worklist
218 bool Changed = false;
219 while (!WorkList.empty()) {
220 AllocationInst *AI = WorkList.back();
223 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
224 // with unused elements.
225 if (AI->use_empty()) {
226 AI->eraseFromParent();
230 // If this alloca is impossible for us to promote, reject it early.
231 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
234 // Check to see if this allocation is only modified by a memcpy/memmove from
235 // a constant global. If this is the case, we can change all users to use
236 // the constant global instead. This is commonly produced by the CFE by
237 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
238 // is only subsequently read.
239 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
240 DOUT << "Found alloca equal to global: " << *AI;
241 DOUT << " memcpy = " << *TheCopy;
242 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
243 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
244 TheCopy->eraseFromParent(); // Don't mutate the global.
245 AI->eraseFromParent();
251 // Check to see if we can perform the core SROA transformation. We cannot
252 // transform the allocation instruction if it is an array allocation
253 // (allocations OF arrays are ok though), and an allocation of a scalar
254 // value cannot be decomposed at all.
255 uint64_t AllocaSize = TD->getTypePaddedSize(AI->getAllocatedType());
257 if ((isa<StructType>(AI->getAllocatedType()) ||
258 isa<ArrayType>(AI->getAllocatedType())) &&
259 // Do not promote any struct whose size is too big.
260 AllocaSize < SRThreshold &&
261 // Do not promote any struct into more than "32" separate vars.
262 getNumSAElements(AI->getAllocatedType()) < SRThreshold/4) {
263 // Check that all of the users of the allocation are capable of being
265 switch (isSafeAllocaToScalarRepl(AI)) {
266 default: assert(0 && "Unexpected value!");
267 case 0: // Not safe to scalar replace.
269 case 1: // Safe, but requires cleanup/canonicalizations first
270 CleanupAllocaUsers(AI);
272 case 3: // Safe to scalar replace.
273 DoScalarReplacement(AI, WorkList);
279 // If we can turn this aggregate value (potentially with casts) into a
280 // simple scalar value that can be mem2reg'd into a register value.
281 // IsNotTrivial tracks whether this is something that mem2reg could have
282 // promoted itself. If so, we don't want to transform it needlessly. Note
283 // that we can't just check based on the type: the alloca may be of an i32
284 // but that has pointer arithmetic to set byte 3 of it or something.
285 bool IsNotTrivial = false;
286 const Type *VectorTy = 0;
287 bool HadAVector = false;
288 if (CanConvertToScalar(AI, IsNotTrivial, VectorTy, HadAVector,
289 0, unsigned(AllocaSize)) && IsNotTrivial) {
291 // If we were able to find a vector type that can handle this with
292 // insert/extract elements, and if there was at least one use that had
293 // a vector type, promote this to a vector. We don't want to promote
294 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
295 // we just get a lot of insert/extracts. If at least one vector is
296 // involved, then we probably really do have a union of vector/array.
297 if (VectorTy && isa<VectorType>(VectorTy) && HadAVector) {
298 DOUT << "CONVERT TO VECTOR: " << *AI << " TYPE = " << *VectorTy <<"\n";
300 // Create and insert the vector alloca.
301 NewAI = new AllocaInst(VectorTy, 0, "", AI->getParent()->begin());
302 ConvertUsesToScalar(AI, NewAI, 0);
304 DOUT << "CONVERT TO SCALAR INTEGER: " << *AI << "\n";
306 // Create and insert the integer alloca.
307 const Type *NewTy = IntegerType::get(AllocaSize*8);
308 NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
309 ConvertUsesToScalar(AI, NewAI, 0);
312 AI->eraseFromParent();
318 // Otherwise, couldn't process this alloca.
324 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
325 /// predicate, do SROA now.
326 void SROA::DoScalarReplacement(AllocationInst *AI,
327 std::vector<AllocationInst*> &WorkList) {
328 DOUT << "Found inst to SROA: " << *AI;
329 SmallVector<AllocaInst*, 32> ElementAllocas;
330 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
331 ElementAllocas.reserve(ST->getNumContainedTypes());
332 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
333 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
335 AI->getName() + "." + utostr(i), AI);
336 ElementAllocas.push_back(NA);
337 WorkList.push_back(NA); // Add to worklist for recursive processing
340 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
341 ElementAllocas.reserve(AT->getNumElements());
342 const Type *ElTy = AT->getElementType();
343 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
344 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
345 AI->getName() + "." + utostr(i), AI);
346 ElementAllocas.push_back(NA);
347 WorkList.push_back(NA); // Add to worklist for recursive processing
351 // Now that we have created the alloca instructions that we want to use,
352 // expand the getelementptr instructions to use them.
354 while (!AI->use_empty()) {
355 Instruction *User = cast<Instruction>(AI->use_back());
356 if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
357 RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
358 BCInst->eraseFromParent();
363 // %res = load { i32, i32 }* %alloc
365 // %load.0 = load i32* %alloc.0
366 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
367 // %load.1 = load i32* %alloc.1
368 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
369 // (Also works for arrays instead of structs)
370 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
371 Value *Insert = UndefValue::get(LI->getType());
372 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
373 Value *Load = new LoadInst(ElementAllocas[i], "load", LI);
374 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
376 LI->replaceAllUsesWith(Insert);
377 LI->eraseFromParent();
382 // store { i32, i32 } %val, { i32, i32 }* %alloc
384 // %val.0 = extractvalue { i32, i32 } %val, 0
385 // store i32 %val.0, i32* %alloc.0
386 // %val.1 = extractvalue { i32, i32 } %val, 1
387 // store i32 %val.1, i32* %alloc.1
388 // (Also works for arrays instead of structs)
389 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
390 Value *Val = SI->getOperand(0);
391 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
392 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
393 new StoreInst(Extract, ElementAllocas[i], SI);
395 SI->eraseFromParent();
399 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
400 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
402 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
404 assert(Idx < ElementAllocas.size() && "Index out of range?");
405 AllocaInst *AllocaToUse = ElementAllocas[Idx];
408 if (GEPI->getNumOperands() == 3) {
409 // Do not insert a new getelementptr instruction with zero indices, only
410 // to have it optimized out later.
411 RepValue = AllocaToUse;
413 // We are indexing deeply into the structure, so we still need a
414 // getelement ptr instruction to finish the indexing. This may be
415 // expanded itself once the worklist is rerun.
417 SmallVector<Value*, 8> NewArgs;
418 NewArgs.push_back(Constant::getNullValue(Type::Int32Ty));
419 NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
420 RepValue = GetElementPtrInst::Create(AllocaToUse, NewArgs.begin(),
421 NewArgs.end(), "", GEPI);
422 RepValue->takeName(GEPI);
425 // If this GEP is to the start of the aggregate, check for memcpys.
426 if (Idx == 0 && GEPI->hasAllZeroIndices())
427 RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas);
429 // Move all of the users over to the new GEP.
430 GEPI->replaceAllUsesWith(RepValue);
431 // Delete the old GEP
432 GEPI->eraseFromParent();
435 // Finally, delete the Alloca instruction
436 AI->eraseFromParent();
441 /// isSafeElementUse - Check to see if this use is an allowed use for a
442 /// getelementptr instruction of an array aggregate allocation. isFirstElt
443 /// indicates whether Ptr is known to the start of the aggregate.
445 void SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
447 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
449 Instruction *User = cast<Instruction>(*I);
450 switch (User->getOpcode()) {
451 case Instruction::Load: break;
452 case Instruction::Store:
453 // Store is ok if storing INTO the pointer, not storing the pointer
454 if (User->getOperand(0) == Ptr) return MarkUnsafe(Info);
456 case Instruction::GetElementPtr: {
457 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
458 bool AreAllZeroIndices = isFirstElt;
459 if (GEP->getNumOperands() > 1) {
460 if (!isa<ConstantInt>(GEP->getOperand(1)) ||
461 !cast<ConstantInt>(GEP->getOperand(1))->isZero())
462 // Using pointer arithmetic to navigate the array.
463 return MarkUnsafe(Info);
465 if (AreAllZeroIndices)
466 AreAllZeroIndices = GEP->hasAllZeroIndices();
468 isSafeElementUse(GEP, AreAllZeroIndices, AI, Info);
469 if (Info.isUnsafe) return;
472 case Instruction::BitCast:
474 isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI, Info);
475 if (Info.isUnsafe) return;
478 DOUT << " Transformation preventing inst: " << *User;
479 return MarkUnsafe(Info);
480 case Instruction::Call:
481 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
483 isSafeMemIntrinsicOnAllocation(MI, AI, I.getOperandNo(), Info);
484 if (Info.isUnsafe) return;
488 DOUT << " Transformation preventing inst: " << *User;
489 return MarkUnsafe(Info);
491 DOUT << " Transformation preventing inst: " << *User;
492 return MarkUnsafe(Info);
495 return; // All users look ok :)
498 /// AllUsersAreLoads - Return true if all users of this value are loads.
499 static bool AllUsersAreLoads(Value *Ptr) {
500 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
502 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
507 /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
508 /// aggregate allocation.
510 void SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
512 if (BitCastInst *C = dyn_cast<BitCastInst>(User))
513 return isSafeUseOfBitCastedAllocation(C, AI, Info);
515 if (LoadInst *LI = dyn_cast<LoadInst>(User))
516 if (!LI->isVolatile())
517 return;// Loads (returning a first class aggregrate) are always rewritable
519 if (StoreInst *SI = dyn_cast<StoreInst>(User))
520 if (!SI->isVolatile() && SI->getOperand(0) != AI)
521 return;// Store is ok if storing INTO the pointer, not storing the pointer
523 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User);
525 return MarkUnsafe(Info);
527 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
529 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
531 I.getOperand() != Constant::getNullValue(I.getOperand()->getType())) {
532 return MarkUnsafe(Info);
536 if (I == E) return MarkUnsafe(Info); // ran out of GEP indices??
538 bool IsAllZeroIndices = true;
540 // If the first index is a non-constant index into an array, see if we can
541 // handle it as a special case.
542 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
543 if (!isa<ConstantInt>(I.getOperand())) {
544 IsAllZeroIndices = 0;
545 uint64_t NumElements = AT->getNumElements();
547 // If this is an array index and the index is not constant, we cannot
548 // promote... that is unless the array has exactly one or two elements in
549 // it, in which case we CAN promote it, but we have to canonicalize this
550 // out if this is the only problem.
551 if ((NumElements == 1 || NumElements == 2) &&
552 AllUsersAreLoads(GEPI)) {
553 Info.needsCleanup = true;
554 return; // Canonicalization required!
556 return MarkUnsafe(Info);
560 // Walk through the GEP type indices, checking the types that this indexes
562 for (; I != E; ++I) {
563 // Ignore struct elements, no extra checking needed for these.
564 if (isa<StructType>(*I))
567 ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
568 if (!IdxVal) return MarkUnsafe(Info);
570 // Are all indices still zero?
571 IsAllZeroIndices &= IdxVal->isZero();
573 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
574 // This GEP indexes an array. Verify that this is an in-range constant
575 // integer. Specifically, consider A[0][i]. We cannot know that the user
576 // isn't doing invalid things like allowing i to index an out-of-range
577 // subscript that accesses A[1]. Because of this, we have to reject SROA
578 // of any accesses into structs where any of the components are variables.
579 if (IdxVal->getZExtValue() >= AT->getNumElements())
580 return MarkUnsafe(Info);
581 } else if (const VectorType *VT = dyn_cast<VectorType>(*I)) {
582 if (IdxVal->getZExtValue() >= VT->getNumElements())
583 return MarkUnsafe(Info);
587 // If there are any non-simple uses of this getelementptr, make sure to reject
589 return isSafeElementUse(GEPI, IsAllZeroIndices, AI, Info);
592 /// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
593 /// intrinsic can be promoted by SROA. At this point, we know that the operand
594 /// of the memintrinsic is a pointer to the beginning of the allocation.
595 void SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
596 unsigned OpNo, AllocaInfo &Info) {
597 // If not constant length, give up.
598 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
599 if (!Length) return MarkUnsafe(Info);
601 // If not the whole aggregate, give up.
602 if (Length->getZExtValue() !=
603 TD->getTypePaddedSize(AI->getType()->getElementType()))
604 return MarkUnsafe(Info);
606 // We only know about memcpy/memset/memmove.
607 if (!isa<MemCpyInst>(MI) && !isa<MemSetInst>(MI) && !isa<MemMoveInst>(MI))
608 return MarkUnsafe(Info);
610 // Otherwise, we can transform it. Determine whether this is a memcpy/set
611 // into or out of the aggregate.
613 Info.isMemCpyDst = true;
616 Info.isMemCpySrc = true;
620 /// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
622 void SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI,
624 for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
626 if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
627 isSafeUseOfBitCastedAllocation(BCU, AI, Info);
628 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
629 isSafeMemIntrinsicOnAllocation(MI, AI, UI.getOperandNo(), Info);
630 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
631 if (SI->isVolatile())
632 return MarkUnsafe(Info);
634 // If storing the entire alloca in one chunk through a bitcasted pointer
635 // to integer, we can transform it. This happens (for example) when you
636 // cast a {i32,i32}* to i64* and store through it. This is similar to the
637 // memcpy case and occurs in various "byval" cases and emulated memcpys.
638 if (isa<IntegerType>(SI->getOperand(0)->getType()) &&
639 TD->getTypePaddedSize(SI->getOperand(0)->getType()) ==
640 TD->getTypePaddedSize(AI->getType()->getElementType())) {
641 Info.isMemCpyDst = true;
644 return MarkUnsafe(Info);
645 } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
646 if (LI->isVolatile())
647 return MarkUnsafe(Info);
649 // If loading the entire alloca in one chunk through a bitcasted pointer
650 // to integer, we can transform it. This happens (for example) when you
651 // cast a {i32,i32}* to i64* and load through it. This is similar to the
652 // memcpy case and occurs in various "byval" cases and emulated memcpys.
653 if (isa<IntegerType>(LI->getType()) &&
654 TD->getTypePaddedSize(LI->getType()) ==
655 TD->getTypePaddedSize(AI->getType()->getElementType())) {
656 Info.isMemCpySrc = true;
659 return MarkUnsafe(Info);
660 } else if (isa<DbgInfoIntrinsic>(UI)) {
661 // If one user is DbgInfoIntrinsic then check if all users are
662 // DbgInfoIntrinsics.
663 if (OnlyUsedByDbgInfoIntrinsics(BC)) {
664 Info.needsCleanup = true;
671 return MarkUnsafe(Info);
673 if (Info.isUnsafe) return;
677 /// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
678 /// to its first element. Transform users of the cast to use the new values
680 void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
681 SmallVector<AllocaInst*, 32> &NewElts) {
682 Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
684 Instruction *User = cast<Instruction>(*UI++);
685 if (BitCastInst *BCU = dyn_cast<BitCastInst>(User)) {
686 RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
687 if (BCU->use_empty()) BCU->eraseFromParent();
691 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
692 // This must be memcpy/memmove/memset of the entire aggregate.
693 // Split into one per element.
694 RewriteMemIntrinUserOfAlloca(MI, BCInst, AI, NewElts);
698 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
699 // If this is a store of the entire alloca from an integer, rewrite it.
700 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
704 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
705 // If this is a load of the entire alloca to an integer, rewrite it.
706 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
710 // Otherwise it must be some other user of a gep of the first pointer. Just
711 // leave these alone.
716 /// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
717 /// Rewrite it to copy or set the elements of the scalarized memory.
718 void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
720 SmallVector<AllocaInst*, 32> &NewElts) {
722 // If this is a memcpy/memmove, construct the other pointer as the
725 if (MemCpyInst *MCI = dyn_cast<MemCpyInst>(MI)) {
726 if (BCInst == MCI->getRawDest())
727 OtherPtr = MCI->getRawSource();
729 assert(BCInst == MCI->getRawSource());
730 OtherPtr = MCI->getRawDest();
732 } else if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
733 if (BCInst == MMI->getRawDest())
734 OtherPtr = MMI->getRawSource();
736 assert(BCInst == MMI->getRawSource());
737 OtherPtr = MMI->getRawDest();
741 // If there is an other pointer, we want to convert it to the same pointer
742 // type as AI has, so we can GEP through it safely.
744 // It is likely that OtherPtr is a bitcast, if so, remove it.
745 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
746 OtherPtr = BC->getOperand(0);
747 // All zero GEPs are effectively bitcasts.
748 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr))
749 if (GEP->hasAllZeroIndices())
750 OtherPtr = GEP->getOperand(0);
752 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
753 if (BCE->getOpcode() == Instruction::BitCast)
754 OtherPtr = BCE->getOperand(0);
756 // If the pointer is not the right type, insert a bitcast to the right
758 if (OtherPtr->getType() != AI->getType())
759 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
763 // Process each element of the aggregate.
764 Value *TheFn = MI->getOperand(0);
765 const Type *BytePtrTy = MI->getRawDest()->getType();
766 bool SROADest = MI->getRawDest() == BCInst;
768 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
770 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
771 // If this is a memcpy/memmove, emit a GEP of the other element address.
774 Value *Idx[2] = { Zero, ConstantInt::get(Type::Int32Ty, i) };
775 OtherElt = GetElementPtrInst::Create(OtherPtr, Idx, Idx + 2,
776 OtherPtr->getNameStr()+"."+utostr(i),
780 Value *EltPtr = NewElts[i];
781 const Type *EltTy =cast<PointerType>(EltPtr->getType())->getElementType();
783 // If we got down to a scalar, insert a load or store as appropriate.
784 if (EltTy->isSingleValueType()) {
785 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
786 Value *Elt = new LoadInst(SROADest ? OtherElt : EltPtr, "tmp",
788 new StoreInst(Elt, SROADest ? EltPtr : OtherElt, MI);
791 assert(isa<MemSetInst>(MI));
793 // If the stored element is zero (common case), just store a null
796 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
798 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
800 // If EltTy is a vector type, get the element type.
801 const Type *ValTy = EltTy;
802 if (const VectorType *VTy = dyn_cast<VectorType>(ValTy))
803 ValTy = VTy->getElementType();
805 // Construct an integer with the right value.
806 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
807 APInt OneVal(EltSize, CI->getZExtValue());
808 APInt TotalVal(OneVal);
810 for (unsigned i = 0; 8*i < EltSize; ++i) {
811 TotalVal = TotalVal.shl(8);
815 // Convert the integer value to the appropriate type.
816 StoreVal = ConstantInt::get(TotalVal);
817 if (isa<PointerType>(ValTy))
818 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
819 else if (ValTy->isFloatingPoint())
820 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
821 assert(StoreVal->getType() == ValTy && "Type mismatch!");
823 // If the requested value was a vector constant, create it.
824 if (EltTy != ValTy) {
825 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
826 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
827 StoreVal = ConstantVector::get(&Elts[0], NumElts);
830 new StoreInst(StoreVal, EltPtr, MI);
833 // Otherwise, if we're storing a byte variable, use a memset call for
837 // Cast the element pointer to BytePtrTy.
838 if (EltPtr->getType() != BytePtrTy)
839 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
841 // Cast the other pointer (if we have one) to BytePtrTy.
842 if (OtherElt && OtherElt->getType() != BytePtrTy)
843 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
846 unsigned EltSize = TD->getTypePaddedSize(EltTy);
848 // Finally, insert the meminst for this element.
849 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
851 SROADest ? EltPtr : OtherElt, // Dest ptr
852 SROADest ? OtherElt : EltPtr, // Src ptr
853 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
856 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
858 assert(isa<MemSetInst>(MI));
860 EltPtr, MI->getOperand(2), // Dest, Value,
861 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
864 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
867 MI->eraseFromParent();
870 /// RewriteStoreUserOfWholeAlloca - We found an store of an integer that
871 /// overwrites the entire allocation. Extract out the pieces of the stored
872 /// integer and store them individually.
873 void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI,
875 SmallVector<AllocaInst*, 32> &NewElts){
876 // Extract each element out of the integer according to its structure offset
877 // and store the element value to the individual alloca.
878 Value *SrcVal = SI->getOperand(0);
879 const Type *AllocaEltTy = AI->getType()->getElementType();
880 uint64_t AllocaSizeBits = TD->getTypePaddedSizeInBits(AllocaEltTy);
882 // If this isn't a store of an integer to the whole alloca, it may be a store
883 // to the first element. Just ignore the store in this case and normal SROA
885 if (!isa<IntegerType>(SrcVal->getType()) ||
886 TD->getTypePaddedSizeInBits(SrcVal->getType()) != AllocaSizeBits)
889 DOUT << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << *SI;
891 // There are two forms here: AI could be an array or struct. Both cases
892 // have different ways to compute the element offset.
893 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
894 const StructLayout *Layout = TD->getStructLayout(EltSTy);
896 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
897 // Get the number of bits to shift SrcVal to get the value.
898 const Type *FieldTy = EltSTy->getElementType(i);
899 uint64_t Shift = Layout->getElementOffsetInBits(i);
901 if (TD->isBigEndian())
902 Shift = AllocaSizeBits-Shift-TD->getTypePaddedSizeInBits(FieldTy);
904 Value *EltVal = SrcVal;
906 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
907 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
908 "sroa.store.elt", SI);
911 // Truncate down to an integer of the right size.
912 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
914 // Ignore zero sized fields like {}, they obviously contain no data.
915 if (FieldSizeBits == 0) continue;
917 if (FieldSizeBits != AllocaSizeBits)
918 EltVal = new TruncInst(EltVal, IntegerType::get(FieldSizeBits), "", SI);
919 Value *DestField = NewElts[i];
920 if (EltVal->getType() == FieldTy) {
921 // Storing to an integer field of this size, just do it.
922 } else if (FieldTy->isFloatingPoint() || isa<VectorType>(FieldTy)) {
923 // Bitcast to the right element type (for fp/vector values).
924 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
926 // Otherwise, bitcast the dest pointer (for aggregates).
927 DestField = new BitCastInst(DestField,
928 PointerType::getUnqual(EltVal->getType()),
931 new StoreInst(EltVal, DestField, SI);
935 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
936 const Type *ArrayEltTy = ATy->getElementType();
937 uint64_t ElementOffset = TD->getTypePaddedSizeInBits(ArrayEltTy);
938 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
942 if (TD->isBigEndian())
943 Shift = AllocaSizeBits-ElementOffset;
947 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
948 // Ignore zero sized fields like {}, they obviously contain no data.
949 if (ElementSizeBits == 0) continue;
951 Value *EltVal = SrcVal;
953 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
954 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
955 "sroa.store.elt", SI);
958 // Truncate down to an integer of the right size.
959 if (ElementSizeBits != AllocaSizeBits)
960 EltVal = new TruncInst(EltVal, IntegerType::get(ElementSizeBits),"",SI);
961 Value *DestField = NewElts[i];
962 if (EltVal->getType() == ArrayEltTy) {
963 // Storing to an integer field of this size, just do it.
964 } else if (ArrayEltTy->isFloatingPoint() || isa<VectorType>(ArrayEltTy)) {
965 // Bitcast to the right element type (for fp/vector values).
966 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
968 // Otherwise, bitcast the dest pointer (for aggregates).
969 DestField = new BitCastInst(DestField,
970 PointerType::getUnqual(EltVal->getType()),
973 new StoreInst(EltVal, DestField, SI);
975 if (TD->isBigEndian())
976 Shift -= ElementOffset;
978 Shift += ElementOffset;
982 SI->eraseFromParent();
985 /// RewriteLoadUserOfWholeAlloca - We found an load of the entire allocation to
986 /// an integer. Load the individual pieces to form the aggregate value.
987 void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
988 SmallVector<AllocaInst*, 32> &NewElts) {
989 // Extract each element out of the NewElts according to its structure offset
990 // and form the result value.
991 const Type *AllocaEltTy = AI->getType()->getElementType();
992 uint64_t AllocaSizeBits = TD->getTypePaddedSizeInBits(AllocaEltTy);
994 // If this isn't a load of the whole alloca to an integer, it may be a load
995 // of the first element. Just ignore the load in this case and normal SROA
997 if (!isa<IntegerType>(LI->getType()) ||
998 TD->getTypePaddedSizeInBits(LI->getType()) != AllocaSizeBits)
1001 DOUT << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << *LI;
1003 // There are two forms here: AI could be an array or struct. Both cases
1004 // have different ways to compute the element offset.
1005 const StructLayout *Layout = 0;
1006 uint64_t ArrayEltBitOffset = 0;
1007 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1008 Layout = TD->getStructLayout(EltSTy);
1010 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
1011 ArrayEltBitOffset = TD->getTypePaddedSizeInBits(ArrayEltTy);
1014 Value *ResultVal = Constant::getNullValue(LI->getType());
1016 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1017 // Load the value from the alloca. If the NewElt is an aggregate, cast
1018 // the pointer to an integer of the same size before doing the load.
1019 Value *SrcField = NewElts[i];
1020 const Type *FieldTy =
1021 cast<PointerType>(SrcField->getType())->getElementType();
1022 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1024 // Ignore zero sized fields like {}, they obviously contain no data.
1025 if (FieldSizeBits == 0) continue;
1027 const IntegerType *FieldIntTy = IntegerType::get(FieldSizeBits);
1028 if (!isa<IntegerType>(FieldTy) && !FieldTy->isFloatingPoint() &&
1029 !isa<VectorType>(FieldTy))
1030 SrcField = new BitCastInst(SrcField, PointerType::getUnqual(FieldIntTy),
1032 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1034 // If SrcField is a fp or vector of the right size but that isn't an
1035 // integer type, bitcast to an integer so we can shift it.
1036 if (SrcField->getType() != FieldIntTy)
1037 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1039 // Zero extend the field to be the same size as the final alloca so that
1040 // we can shift and insert it.
1041 if (SrcField->getType() != ResultVal->getType())
1042 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1044 // Determine the number of bits to shift SrcField.
1046 if (Layout) // Struct case.
1047 Shift = Layout->getElementOffsetInBits(i);
1049 Shift = i*ArrayEltBitOffset;
1051 if (TD->isBigEndian())
1052 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1055 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
1056 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1059 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1062 LI->replaceAllUsesWith(ResultVal);
1063 LI->eraseFromParent();
1067 /// HasPadding - Return true if the specified type has any structure or
1068 /// alignment padding, false otherwise.
1069 static bool HasPadding(const Type *Ty, const TargetData &TD) {
1070 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1071 const StructLayout *SL = TD.getStructLayout(STy);
1072 unsigned PrevFieldBitOffset = 0;
1073 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1074 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1076 // Padding in sub-elements?
1077 if (HasPadding(STy->getElementType(i), TD))
1080 // Check to see if there is any padding between this element and the
1083 unsigned PrevFieldEnd =
1084 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1085 if (PrevFieldEnd < FieldBitOffset)
1089 PrevFieldBitOffset = FieldBitOffset;
1092 // Check for tail padding.
1093 if (unsigned EltCount = STy->getNumElements()) {
1094 unsigned PrevFieldEnd = PrevFieldBitOffset +
1095 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
1096 if (PrevFieldEnd < SL->getSizeInBits())
1100 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1101 return HasPadding(ATy->getElementType(), TD);
1102 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1103 return HasPadding(VTy->getElementType(), TD);
1105 return TD.getTypeSizeInBits(Ty) != TD.getTypePaddedSizeInBits(Ty);
1108 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1109 /// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1110 /// or 1 if safe after canonicalization has been performed.
1112 int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
1113 // Loop over the use list of the alloca. We can only transform it if all of
1114 // the users are safe to transform.
1117 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
1119 isSafeUseOfAllocation(cast<Instruction>(*I), AI, Info);
1120 if (Info.isUnsafe) {
1121 DOUT << "Cannot transform: " << *AI << " due to user: " << **I;
1126 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1127 // source and destination, we have to be careful. In particular, the memcpy
1128 // could be moving around elements that live in structure padding of the LLVM
1129 // types, but may actually be used. In these cases, we refuse to promote the
1131 if (Info.isMemCpySrc && Info.isMemCpyDst &&
1132 HasPadding(AI->getType()->getElementType(), *TD))
1135 // If we require cleanup, return 1, otherwise return 3.
1136 return Info.needsCleanup ? 1 : 3;
1139 /// CleanupGEP - GEP is used by an Alloca, which can be prompted after the GEP
1140 /// is canonicalized here.
1141 void SROA::CleanupGEP(GetElementPtrInst *GEPI) {
1142 gep_type_iterator I = gep_type_begin(GEPI);
1145 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
1146 uint64_t NumElements = AT->getNumElements();
1148 if (!isa<ConstantInt>(I.getOperand())) {
1149 if (NumElements == 1) {
1150 GEPI->setOperand(2, Constant::getNullValue(Type::Int32Ty));
1152 assert(NumElements == 2 && "Unhandled case!");
1153 // All users of the GEP must be loads. At each use of the GEP, insert
1154 // two loads of the appropriate indexed GEP and select between them.
1155 Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(),
1156 Constant::getNullValue(I.getOperand()->getType()),
1158 // Insert the new GEP instructions, which are properly indexed.
1159 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
1160 Indices[1] = Constant::getNullValue(Type::Int32Ty);
1161 Value *ZeroIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1164 GEPI->getName()+".0", GEPI);
1165 Indices[1] = ConstantInt::get(Type::Int32Ty, 1);
1166 Value *OneIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1169 GEPI->getName()+".1", GEPI);
1170 // Replace all loads of the variable index GEP with loads from both
1171 // indexes and a select.
1172 while (!GEPI->use_empty()) {
1173 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
1174 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
1175 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
1176 Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI);
1177 LI->replaceAllUsesWith(R);
1178 LI->eraseFromParent();
1180 GEPI->eraseFromParent();
1186 /// CleanupAllocaUsers - If SROA reported that it can promote the specified
1187 /// allocation, but only if cleaned up, perform the cleanups required.
1188 void SROA::CleanupAllocaUsers(AllocationInst *AI) {
1189 // At this point, we know that the end result will be SROA'd and promoted, so
1190 // we can insert ugly code if required so long as sroa+mem2reg will clean it
1192 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1195 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U))
1197 else if (Instruction *I = dyn_cast<Instruction>(U)) {
1198 SmallVector<DbgInfoIntrinsic *, 2> DbgInUses;
1199 if (OnlyUsedByDbgInfoIntrinsics(I, &DbgInUses)) {
1200 // Safe to remove debug info uses.
1201 while (!DbgInUses.empty()) {
1202 DbgInfoIntrinsic *DI = DbgInUses.back(); DbgInUses.pop_back();
1203 DI->eraseFromParent();
1205 I->eraseFromParent();
1211 /// MergeInType - Add the 'In' type to the accumulated type (Accum) so far at
1212 /// the offset specified by Offset (which is specified in bytes).
1214 /// There are two cases we handle here:
1215 /// 1) A union of vector types of the same size and potentially its elements.
1216 /// Here we turn element accesses into insert/extract element operations.
1217 /// This promotes a <4 x float> with a store of float to the third element
1218 /// into a <4 x float> that uses insert element.
1219 /// 2) A fully general blob of memory, which we turn into some (potentially
1220 /// large) integer type with extract and insert operations where the loads
1221 /// and stores would mutate the memory.
1222 static void MergeInType(const Type *In, uint64_t Offset, const Type *&VecTy,
1223 unsigned AllocaSize, const TargetData &TD) {
1224 // If this could be contributing to a vector, analyze it.
1225 if (VecTy != Type::VoidTy) { // either null or a vector type.
1227 // If the In type is a vector that is the same size as the alloca, see if it
1228 // matches the existing VecTy.
1229 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
1230 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
1231 // If we're storing/loading a vector of the right size, allow it as a
1232 // vector. If this the first vector we see, remember the type so that
1233 // we know the element size.
1238 } else if (In == Type::FloatTy || In == Type::DoubleTy ||
1239 (isa<IntegerType>(In) && In->getPrimitiveSizeInBits() >= 8 &&
1240 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
1241 // If we're accessing something that could be an element of a vector, see
1242 // if the implied vector agrees with what we already have and if Offset is
1243 // compatible with it.
1244 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
1245 if (Offset % EltSize == 0 &&
1246 AllocaSize % EltSize == 0 &&
1248 cast<VectorType>(VecTy)->getElementType()
1249 ->getPrimitiveSizeInBits()/8 == EltSize)) {
1251 VecTy = VectorType::get(In, AllocaSize/EltSize);
1257 // Otherwise, we have a case that we can't handle with an optimized vector
1258 // form. We can still turn this into a large integer.
1259 VecTy = Type::VoidTy;
1262 /// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
1263 /// its accesses to use a to single vector type, return true, and set VecTy to
1264 /// the new type. If we could convert the alloca into a single promotable
1265 /// integer, return true but set VecTy to VoidTy. Further, if the use is not a
1266 /// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
1267 /// is the current offset from the base of the alloca being analyzed.
1269 /// If we see at least one access to the value that is as a vector type, set the
1272 bool SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
1273 bool &SawVec, uint64_t Offset,
1274 unsigned AllocaSize) {
1275 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1276 Instruction *User = cast<Instruction>(*UI);
1278 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1279 // Don't break volatile loads.
1280 if (LI->isVolatile())
1282 MergeInType(LI->getType(), Offset, VecTy, AllocaSize, *TD);
1283 SawVec |= isa<VectorType>(LI->getType());
1287 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1288 // Storing the pointer, not into the value?
1289 if (SI->getOperand(0) == V || SI->isVolatile()) return 0;
1290 MergeInType(SI->getOperand(0)->getType(), Offset, VecTy, AllocaSize, *TD);
1291 SawVec |= isa<VectorType>(SI->getOperand(0)->getType());
1295 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
1296 if (!CanConvertToScalar(BCI, IsNotTrivial, VecTy, SawVec, Offset,
1299 IsNotTrivial = true;
1303 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1304 // If this is a GEP with a variable indices, we can't handle it.
1305 if (!GEP->hasAllConstantIndices())
1308 // Compute the offset that this GEP adds to the pointer.
1309 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1310 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1311 &Indices[0], Indices.size());
1312 // See if all uses can be converted.
1313 if (!CanConvertToScalar(GEP, IsNotTrivial, VecTy, SawVec,Offset+GEPOffset,
1316 IsNotTrivial = true;
1320 // If this is a constant sized memset of a constant value (e.g. 0) we can
1322 if (isa<MemSetInst>(User) &&
1323 // Store of constant value.
1324 isa<ConstantInt>(User->getOperand(2)) &&
1325 // Store with constant size.
1326 isa<ConstantInt>(User->getOperand(3))) {
1327 VecTy = Type::VoidTy;
1328 IsNotTrivial = true;
1332 // Otherwise, we cannot handle this!
1340 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
1341 /// directly. This happens when we are converting an "integer union" to a
1342 /// single integer scalar, or when we are converting a "vector union" to a
1343 /// vector with insert/extractelement instructions.
1345 /// Offset is an offset from the original alloca, in bits that need to be
1346 /// shifted to the right. By the end of this, there should be no uses of Ptr.
1347 void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset) {
1348 while (!Ptr->use_empty()) {
1349 Instruction *User = cast<Instruction>(Ptr->use_back());
1351 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
1352 ConvertUsesToScalar(CI, NewAI, Offset);
1353 CI->eraseFromParent();
1357 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1358 // Compute the offset that this GEP adds to the pointer.
1359 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1360 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1361 &Indices[0], Indices.size());
1362 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
1363 GEP->eraseFromParent();
1367 IRBuilder<> Builder(User->getParent(), User);
1369 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1370 // The load is a bit extract from NewAI shifted right by Offset bits.
1371 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
1373 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
1374 LI->replaceAllUsesWith(NewLoadVal);
1375 LI->eraseFromParent();
1379 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1380 assert(SI->getOperand(0) != Ptr && "Consistency error!");
1381 Value *Old = Builder.CreateLoad(NewAI, (NewAI->getName()+".in").c_str());
1382 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
1384 Builder.CreateStore(New, NewAI);
1385 SI->eraseFromParent();
1389 // If this is a constant sized memset of a constant value (e.g. 0) we can
1390 // transform it into a store of the expanded constant value.
1391 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1392 assert(MSI->getRawDest() == Ptr && "Consistency error!");
1393 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
1394 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
1396 // Compute the value replicated the right number of times.
1397 APInt APVal(NumBytes*8, Val);
1399 // Splat the value if non-zero.
1401 for (unsigned i = 1; i != NumBytes; ++i)
1402 APVal |= APVal << 8;
1404 Value *Old = Builder.CreateLoad(NewAI, (NewAI->getName()+".in").c_str());
1405 Value *New = ConvertScalar_InsertValue(ConstantInt::get(APVal), Old,
1407 Builder.CreateStore(New, NewAI);
1408 MSI->eraseFromParent();
1413 assert(0 && "Unsupported operation!");
1418 /// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
1419 /// or vector value FromVal, extracting the bits from the offset specified by
1420 /// Offset. This returns the value, which is of type ToType.
1422 /// This happens when we are converting an "integer union" to a single
1423 /// integer scalar, or when we are converting a "vector union" to a vector with
1424 /// insert/extractelement instructions.
1426 /// Offset is an offset from the original alloca, in bits that need to be
1427 /// shifted to the right.
1428 Value *SROA::ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
1429 uint64_t Offset, IRBuilder<> &Builder) {
1430 // If the load is of the whole new alloca, no conversion is needed.
1431 if (FromVal->getType() == ToType && Offset == 0)
1434 // If the result alloca is a vector type, this is either an element
1435 // access or a bitcast to another vector type of the same size.
1436 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
1437 if (isa<VectorType>(ToType))
1438 return Builder.CreateBitCast(FromVal, ToType, "tmp");
1440 // Otherwise it must be an element access.
1443 unsigned EltSize = TD->getTypePaddedSizeInBits(VTy->getElementType());
1444 Elt = Offset/EltSize;
1445 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
1447 // Return the element extracted out of it.
1448 Value *V = Builder.CreateExtractElement(FromVal,
1449 ConstantInt::get(Type::Int32Ty,Elt),
1451 if (V->getType() != ToType)
1452 V = Builder.CreateBitCast(V, ToType, "tmp");
1456 // If ToType is a first class aggregate, extract out each of the pieces and
1457 // use insertvalue's to form the FCA.
1458 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
1459 const StructLayout &Layout = *TD->getStructLayout(ST);
1460 Value *Res = UndefValue::get(ST);
1461 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1462 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
1463 Offset+Layout.getElementOffsetInBits(i),
1465 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1470 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
1471 uint64_t EltSize = TD->getTypePaddedSizeInBits(AT->getElementType());
1472 Value *Res = UndefValue::get(AT);
1473 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1474 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
1475 Offset+i*EltSize, Builder);
1476 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1481 // Otherwise, this must be a union that was converted to an integer value.
1482 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
1484 // If this is a big-endian system and the load is narrower than the
1485 // full alloca type, we need to do a shift to get the right bits.
1487 if (TD->isBigEndian()) {
1488 // On big-endian machines, the lowest bit is stored at the bit offset
1489 // from the pointer given by getTypeStoreSizeInBits. This matters for
1490 // integers with a bitwidth that is not a multiple of 8.
1491 ShAmt = TD->getTypeStoreSizeInBits(NTy) -
1492 TD->getTypeStoreSizeInBits(ToType) - Offset;
1497 // Note: we support negative bitwidths (with shl) which are not defined.
1498 // We do this to support (f.e.) loads off the end of a structure where
1499 // only some bits are used.
1500 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
1501 FromVal = Builder.CreateLShr(FromVal, ConstantInt::get(FromVal->getType(),
1503 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
1504 FromVal = Builder.CreateShl(FromVal, ConstantInt::get(FromVal->getType(),
1507 // Finally, unconditionally truncate the integer to the right width.
1508 unsigned LIBitWidth = TD->getTypeSizeInBits(ToType);
1509 if (LIBitWidth < NTy->getBitWidth())
1510 FromVal = Builder.CreateTrunc(FromVal, IntegerType::get(LIBitWidth), "tmp");
1511 else if (LIBitWidth > NTy->getBitWidth())
1512 FromVal = Builder.CreateZExt(FromVal, IntegerType::get(LIBitWidth), "tmp");
1514 // If the result is an integer, this is a trunc or bitcast.
1515 if (isa<IntegerType>(ToType)) {
1517 } else if (ToType->isFloatingPoint() || isa<VectorType>(ToType)) {
1518 // Just do a bitcast, we know the sizes match up.
1519 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
1521 // Otherwise must be a pointer.
1522 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
1524 assert(FromVal->getType() == ToType && "Didn't convert right?");
1529 /// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
1530 /// or vector value "Old" at the offset specified by Offset.
1532 /// This happens when we are converting an "integer union" to a
1533 /// single integer scalar, or when we are converting a "vector union" to a
1534 /// vector with insert/extractelement instructions.
1536 /// Offset is an offset from the original alloca, in bits that need to be
1537 /// shifted to the right.
1538 Value *SROA::ConvertScalar_InsertValue(Value *SV, Value *Old,
1539 uint64_t Offset, IRBuilder<> &Builder) {
1541 // Convert the stored type to the actual type, shift it left to insert
1542 // then 'or' into place.
1543 const Type *AllocaType = Old->getType();
1545 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
1546 // If the result alloca is a vector type, this is either an element
1547 // access or a bitcast to another vector type.
1548 if (isa<VectorType>(SV->getType())) {
1549 SV = Builder.CreateBitCast(SV, AllocaType, "tmp");
1551 // Must be an element insertion.
1552 unsigned Elt = Offset/TD->getTypePaddedSizeInBits(VTy->getElementType());
1554 if (SV->getType() != VTy->getElementType())
1555 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
1557 SV = Builder.CreateInsertElement(Old, SV,
1558 ConstantInt::get(Type::Int32Ty, Elt),
1564 // If SV is a first-class aggregate value, insert each value recursively.
1565 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
1566 const StructLayout &Layout = *TD->getStructLayout(ST);
1567 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1568 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1569 Old = ConvertScalar_InsertValue(Elt, Old,
1570 Offset+Layout.getElementOffsetInBits(i),
1576 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
1577 uint64_t EltSize = TD->getTypePaddedSizeInBits(AT->getElementType());
1578 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1579 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1580 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
1585 // If SV is a float, convert it to the appropriate integer type.
1586 // If it is a pointer, do the same.
1587 unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1588 unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1589 unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1590 unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
1591 if (SV->getType()->isFloatingPoint() || isa<VectorType>(SV->getType()))
1592 SV = Builder.CreateBitCast(SV, IntegerType::get(SrcWidth), "tmp");
1593 else if (isa<PointerType>(SV->getType()))
1594 SV = Builder.CreatePtrToInt(SV, TD->getIntPtrType(), "tmp");
1596 // Zero extend or truncate the value if needed.
1597 if (SV->getType() != AllocaType) {
1598 if (SV->getType()->getPrimitiveSizeInBits() <
1599 AllocaType->getPrimitiveSizeInBits())
1600 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
1602 // Truncation may be needed if storing more than the alloca can hold
1603 // (undefined behavior).
1604 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
1605 SrcWidth = DestWidth;
1606 SrcStoreWidth = DestStoreWidth;
1610 // If this is a big-endian system and the store is narrower than the
1611 // full alloca type, we need to do a shift to get the right bits.
1613 if (TD->isBigEndian()) {
1614 // On big-endian machines, the lowest bit is stored at the bit offset
1615 // from the pointer given by getTypeStoreSizeInBits. This matters for
1616 // integers with a bitwidth that is not a multiple of 8.
1617 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
1622 // Note: we support negative bitwidths (with shr) which are not defined.
1623 // We do this to support (f.e.) stores off the end of a structure where
1624 // only some bits in the structure are set.
1625 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1626 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1627 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(), ShAmt), "tmp");
1629 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1630 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(), -ShAmt), "tmp");
1631 Mask = Mask.lshr(-ShAmt);
1634 // Mask out the bits we are about to insert from the old value, and or
1636 if (SrcWidth != DestWidth) {
1637 assert(DestWidth > SrcWidth);
1638 Old = Builder.CreateAnd(Old, ConstantInt::get(~Mask), "mask");
1639 SV = Builder.CreateOr(Old, SV, "ins");
1646 /// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1647 /// some part of a constant global variable. This intentionally only accepts
1648 /// constant expressions because we don't can't rewrite arbitrary instructions.
1649 static bool PointsToConstantGlobal(Value *V) {
1650 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1651 return GV->isConstant();
1652 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1653 if (CE->getOpcode() == Instruction::BitCast ||
1654 CE->getOpcode() == Instruction::GetElementPtr)
1655 return PointsToConstantGlobal(CE->getOperand(0));
1659 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1660 /// pointer to an alloca. Ignore any reads of the pointer, return false if we
1661 /// see any stores or other unknown uses. If we see pointer arithmetic, keep
1662 /// track of whether it moves the pointer (with isOffset) but otherwise traverse
1663 /// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1664 /// the alloca, and if the source pointer is a pointer to a constant global, we
1665 /// can optimize this.
1666 static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1668 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1669 if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
1670 // Ignore non-volatile loads, they are always ok.
1671 if (!LI->isVolatile())
1674 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1675 // If uses of the bitcast are ok, we are ok.
1676 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1680 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1681 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1682 // doesn't, it does.
1683 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1684 isOffset || !GEP->hasAllZeroIndices()))
1689 // If this is isn't our memcpy/memmove, reject it as something we can't
1691 if (!isa<MemCpyInst>(*UI) && !isa<MemMoveInst>(*UI))
1694 // If we already have seen a copy, reject the second one.
1695 if (TheCopy) return false;
1697 // If the pointer has been offset from the start of the alloca, we can't
1698 // safely handle this.
1699 if (isOffset) return false;
1701 // If the memintrinsic isn't using the alloca as the dest, reject it.
1702 if (UI.getOperandNo() != 1) return false;
1704 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1706 // If the source of the memcpy/move is not a constant global, reject it.
1707 if (!PointsToConstantGlobal(MI->getOperand(2)))
1710 // Otherwise, the transform is safe. Remember the copy instruction.
1716 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1717 /// modified by a copy from a constant global. If we can prove this, we can
1718 /// replace any uses of the alloca with uses of the global directly.
1719 Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocationInst *AI) {
1720 Instruction *TheCopy = 0;
1721 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))