1 //===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/Pass.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Analysis/Dominators.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/GetElementPtrTypeIterator.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/Compiler.h"
36 #include "llvm/ADT/SmallVector.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/ADT/StringExtras.h"
41 STATISTIC(NumReplaced, "Number of allocas broken up");
42 STATISTIC(NumPromoted, "Number of allocas promoted");
43 STATISTIC(NumConverted, "Number of aggregates converted to scalar");
46 struct VISIBILITY_HIDDEN SROA : public FunctionPass {
47 bool runOnFunction(Function &F);
49 bool performScalarRepl(Function &F);
50 bool performPromotion(Function &F);
52 // getAnalysisUsage - This pass does not require any passes, but we know it
53 // will not alter the CFG, so say so.
54 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
55 AU.addRequired<DominatorTree>();
56 AU.addRequired<DominanceFrontier>();
57 AU.addRequired<TargetData>();
62 int isSafeElementUse(Value *Ptr);
63 int isSafeUseOfAllocation(Instruction *User);
64 int isSafeAllocaToScalarRepl(AllocationInst *AI);
65 void CanonicalizeAllocaUsers(AllocationInst *AI);
66 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
68 const Type *CanConvertToScalar(Value *V, bool &IsNotTrivial);
69 void ConvertToScalar(AllocationInst *AI, const Type *Ty);
70 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset);
73 RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
76 // Public interface to the ScalarReplAggregates pass
77 FunctionPass *llvm::createScalarReplAggregatesPass() { return new SROA(); }
80 bool SROA::runOnFunction(Function &F) {
81 bool Changed = performPromotion(F);
83 bool LocalChange = performScalarRepl(F);
84 if (!LocalChange) break; // No need to repromote if no scalarrepl
86 LocalChange = performPromotion(F);
87 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
94 bool SROA::performPromotion(Function &F) {
95 std::vector<AllocaInst*> Allocas;
96 const TargetData &TD = getAnalysis<TargetData>();
97 DominatorTree &DT = getAnalysis<DominatorTree>();
98 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
100 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
102 bool Changed = false;
107 // Find allocas that are safe to promote, by looking at all instructions in
109 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
110 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
111 if (isAllocaPromotable(AI, TD))
112 Allocas.push_back(AI);
114 if (Allocas.empty()) break;
116 PromoteMemToReg(Allocas, DT, DF, TD);
117 NumPromoted += Allocas.size();
124 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
125 // which runs on all of the malloc/alloca instructions in the function, removing
126 // them if they are only used by getelementptr instructions.
128 bool SROA::performScalarRepl(Function &F) {
129 std::vector<AllocationInst*> WorkList;
131 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
132 BasicBlock &BB = F.getEntryBlock();
133 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
134 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
135 WorkList.push_back(A);
137 // Process the worklist
138 bool Changed = false;
139 while (!WorkList.empty()) {
140 AllocationInst *AI = WorkList.back();
143 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
144 // with unused elements.
145 if (AI->use_empty()) {
146 AI->eraseFromParent();
150 // If we can turn this aggregate value (potentially with casts) into a
151 // simple scalar value that can be mem2reg'd into a register value.
152 bool IsNotTrivial = false;
153 if (const Type *ActualType = CanConvertToScalar(AI, IsNotTrivial))
154 if (IsNotTrivial && ActualType != Type::VoidTy) {
155 ConvertToScalar(AI, ActualType);
160 // We cannot transform the allocation instruction if it is an array
161 // allocation (allocations OF arrays are ok though), and an allocation of a
162 // scalar value cannot be decomposed at all.
164 if (AI->isArrayAllocation() ||
165 (!isa<StructType>(AI->getAllocatedType()) &&
166 !isa<ArrayType>(AI->getAllocatedType()))) continue;
168 // Check that all of the users of the allocation are capable of being
170 switch (isSafeAllocaToScalarRepl(AI)) {
171 default: assert(0 && "Unexpected value!");
172 case 0: // Not safe to scalar replace.
174 case 1: // Safe, but requires cleanup/canonicalizations first
175 CanonicalizeAllocaUsers(AI);
176 case 3: // Safe to scalar replace.
180 DOUT << "Found inst to xform: " << *AI;
183 std::vector<AllocaInst*> ElementAllocas;
184 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
185 ElementAllocas.reserve(ST->getNumContainedTypes());
186 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
187 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
189 AI->getName() + "." + utostr(i), AI);
190 ElementAllocas.push_back(NA);
191 WorkList.push_back(NA); // Add to worklist for recursive processing
194 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
195 ElementAllocas.reserve(AT->getNumElements());
196 const Type *ElTy = AT->getElementType();
197 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
198 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
199 AI->getName() + "." + utostr(i), AI);
200 ElementAllocas.push_back(NA);
201 WorkList.push_back(NA); // Add to worklist for recursive processing
205 // Now that we have created the alloca instructions that we want to use,
206 // expand the getelementptr instructions to use them.
208 while (!AI->use_empty()) {
209 Instruction *User = cast<Instruction>(AI->use_back());
210 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
211 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
213 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
215 assert(Idx < ElementAllocas.size() && "Index out of range?");
216 AllocaInst *AllocaToUse = ElementAllocas[Idx];
219 if (GEPI->getNumOperands() == 3) {
220 // Do not insert a new getelementptr instruction with zero indices, only
221 // to have it optimized out later.
222 RepValue = AllocaToUse;
224 // We are indexing deeply into the structure, so we still need a
225 // getelement ptr instruction to finish the indexing. This may be
226 // expanded itself once the worklist is rerun.
228 SmallVector<Value*, 8> NewArgs;
229 NewArgs.push_back(Constant::getNullValue(Type::Int32Ty));
230 NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
231 RepValue = new GetElementPtrInst(AllocaToUse, &NewArgs[0],
232 NewArgs.size(), "", GEPI);
233 RepValue->takeName(GEPI);
236 // Move all of the users over to the new GEP.
237 GEPI->replaceAllUsesWith(RepValue);
238 // Delete the old GEP
239 GEPI->eraseFromParent();
242 // Finally, delete the Alloca instruction
243 AI->eraseFromParent();
251 /// isSafeElementUse - Check to see if this use is an allowed use for a
252 /// getelementptr instruction of an array aggregate allocation.
254 int SROA::isSafeElementUse(Value *Ptr) {
255 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
257 Instruction *User = cast<Instruction>(*I);
258 switch (User->getOpcode()) {
259 case Instruction::Load: break;
260 case Instruction::Store:
261 // Store is ok if storing INTO the pointer, not storing the pointer
262 if (User->getOperand(0) == Ptr) return 0;
264 case Instruction::GetElementPtr: {
265 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
266 if (GEP->getNumOperands() > 1) {
267 if (!isa<Constant>(GEP->getOperand(1)) ||
268 !cast<Constant>(GEP->getOperand(1))->isNullValue())
269 return 0; // Using pointer arithmetic to navigate the array...
271 if (!isSafeElementUse(GEP)) return 0;
275 DOUT << " Transformation preventing inst: " << *User;
279 return 3; // All users look ok :)
282 /// AllUsersAreLoads - Return true if all users of this value are loads.
283 static bool AllUsersAreLoads(Value *Ptr) {
284 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
286 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
291 /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
292 /// aggregate allocation.
294 int SROA::isSafeUseOfAllocation(Instruction *User) {
295 if (!isa<GetElementPtrInst>(User)) return 0;
297 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
298 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
300 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
302 I.getOperand() != Constant::getNullValue(I.getOperand()->getType()))
306 if (I == E) return 0; // ran out of GEP indices??
308 // If this is a use of an array allocation, do a bit more checking for sanity.
309 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
310 uint64_t NumElements = AT->getNumElements();
312 if (isa<ConstantInt>(I.getOperand())) {
313 // Check to make sure that index falls within the array. If not,
314 // something funny is going on, so we won't do the optimization.
316 if (cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue() >= NumElements)
319 // We cannot scalar repl this level of the array unless any array
320 // sub-indices are in-range constants. In particular, consider:
321 // A[0][i]. We cannot know that the user isn't doing invalid things like
322 // allowing i to index an out-of-range subscript that accesses A[1].
324 // Scalar replacing *just* the outer index of the array is probably not
325 // going to be a win anyway, so just give up.
326 for (++I; I != E && (isa<ArrayType>(*I) || isa<VectorType>(*I)); ++I) {
327 uint64_t NumElements;
328 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*I))
329 NumElements = SubArrayTy->getNumElements();
331 NumElements = cast<VectorType>(*I)->getNumElements();
333 if (!isa<ConstantInt>(I.getOperand())) return 0;
334 if (cast<ConstantInt>(I.getOperand())->getZExtValue() >= NumElements)
339 // If this is an array index and the index is not constant, we cannot
340 // promote... that is unless the array has exactly one or two elements in
341 // it, in which case we CAN promote it, but we have to canonicalize this
342 // out if this is the only problem.
343 if ((NumElements == 1 || NumElements == 2) &&
344 AllUsersAreLoads(GEPI))
345 return 1; // Canonicalization required!
350 // If there are any non-simple uses of this getelementptr, make sure to reject
352 return isSafeElementUse(GEPI);
355 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
356 /// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
357 /// or 1 if safe after canonicalization has been performed.
359 int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
360 // Loop over the use list of the alloca. We can only transform it if all of
361 // the users are safe to transform.
364 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
366 isSafe &= isSafeUseOfAllocation(cast<Instruction>(*I));
368 DOUT << "Cannot transform: " << *AI << " due to user: " << **I;
372 // If we require cleanup, isSafe is now 1, otherwise it is 3.
376 /// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified
377 /// allocation, but only if cleaned up, perform the cleanups required.
378 void SROA::CanonicalizeAllocaUsers(AllocationInst *AI) {
379 // At this point, we know that the end result will be SROA'd and promoted, so
380 // we can insert ugly code if required so long as sroa+mem2reg will clean it
382 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
384 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(*UI++);
385 gep_type_iterator I = gep_type_begin(GEPI);
388 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
389 uint64_t NumElements = AT->getNumElements();
391 if (!isa<ConstantInt>(I.getOperand())) {
392 if (NumElements == 1) {
393 GEPI->setOperand(2, Constant::getNullValue(Type::Int32Ty));
395 assert(NumElements == 2 && "Unhandled case!");
396 // All users of the GEP must be loads. At each use of the GEP, insert
397 // two loads of the appropriate indexed GEP and select between them.
398 Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(),
399 Constant::getNullValue(I.getOperand()->getType()),
401 // Insert the new GEP instructions, which are properly indexed.
402 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
403 Indices[1] = Constant::getNullValue(Type::Int32Ty);
404 Value *ZeroIdx = new GetElementPtrInst(GEPI->getOperand(0),
405 &Indices[0], Indices.size(),
406 GEPI->getName()+".0", GEPI);
407 Indices[1] = ConstantInt::get(Type::Int32Ty, 1);
408 Value *OneIdx = new GetElementPtrInst(GEPI->getOperand(0),
409 &Indices[0], Indices.size(),
410 GEPI->getName()+".1", GEPI);
411 // Replace all loads of the variable index GEP with loads from both
412 // indexes and a select.
413 while (!GEPI->use_empty()) {
414 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
415 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
416 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
417 Value *R = new SelectInst(IsOne, One, Zero, LI->getName(), LI);
418 LI->replaceAllUsesWith(R);
419 LI->eraseFromParent();
421 GEPI->eraseFromParent();
428 /// MergeInType - Add the 'In' type to the accumulated type so far. If the
429 /// types are incompatible, return true, otherwise update Accum and return
432 /// There are three cases we handle here:
433 /// 1) An effectively-integer union, where the pieces are stored into as
434 /// smaller integers (common with byte swap and other idioms).
435 /// 2) A union of vector types of the same size and potentially its elements.
436 /// Here we turn element accesses into insert/extract element operations.
437 /// 3) A union of scalar types, such as int/float or int/pointer. Here we
438 /// merge together into integers, allowing the xform to work with #1 as
440 static bool MergeInType(const Type *In, const Type *&Accum,
441 const TargetData &TD) {
442 // If this is our first type, just use it.
443 const VectorType *PTy;
444 if (Accum == Type::VoidTy || In == Accum) {
446 } else if (In == Type::VoidTy) {
448 } else if (In->isInteger() && Accum->isInteger()) { // integer union.
449 // Otherwise pick whichever type is larger.
450 if (cast<IntegerType>(In)->getBitWidth() >
451 cast<IntegerType>(Accum)->getBitWidth())
453 } else if (isa<PointerType>(In) && isa<PointerType>(Accum)) {
454 // Pointer unions just stay as one of the pointers.
455 } else if (isa<VectorType>(In) || isa<VectorType>(Accum)) {
456 if ((PTy = dyn_cast<VectorType>(Accum)) &&
457 PTy->getElementType() == In) {
458 // Accum is a vector, and we are accessing an element: ok.
459 } else if ((PTy = dyn_cast<VectorType>(In)) &&
460 PTy->getElementType() == Accum) {
461 // In is a vector, and accum is an element: ok, remember In.
463 } else if ((PTy = dyn_cast<VectorType>(In)) && isa<VectorType>(Accum) &&
464 PTy->getBitWidth() == cast<VectorType>(Accum)->getBitWidth()) {
465 // Two vectors of the same size: keep Accum.
467 // Cannot insert an short into a <4 x int> or handle
468 // <2 x int> -> <4 x int>
472 // Pointer/FP/Integer unions merge together as integers.
473 switch (Accum->getTypeID()) {
474 case Type::PointerTyID: Accum = TD.getIntPtrType(); break;
475 case Type::FloatTyID: Accum = Type::Int32Ty; break;
476 case Type::DoubleTyID: Accum = Type::Int64Ty; break;
478 assert(Accum->isInteger() && "Unknown FP type!");
482 switch (In->getTypeID()) {
483 case Type::PointerTyID: In = TD.getIntPtrType(); break;
484 case Type::FloatTyID: In = Type::Int32Ty; break;
485 case Type::DoubleTyID: In = Type::Int64Ty; break;
487 assert(In->isInteger() && "Unknown FP type!");
490 return MergeInType(In, Accum, TD);
495 /// getUIntAtLeastAsBitAs - Return an unsigned integer type that is at least
496 /// as big as the specified type. If there is no suitable type, this returns
498 const Type *getUIntAtLeastAsBitAs(unsigned NumBits) {
499 if (NumBits > 64) return 0;
500 if (NumBits > 32) return Type::Int64Ty;
501 if (NumBits > 16) return Type::Int32Ty;
502 if (NumBits > 8) return Type::Int16Ty;
506 /// CanConvertToScalar - V is a pointer. If we can convert the pointee to a
507 /// single scalar integer type, return that type. Further, if the use is not
508 /// a completely trivial use that mem2reg could promote, set IsNotTrivial. If
509 /// there are no uses of this pointer, return Type::VoidTy to differentiate from
512 const Type *SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial) {
513 const Type *UsedType = Type::VoidTy; // No uses, no forced type.
514 const TargetData &TD = getAnalysis<TargetData>();
515 const PointerType *PTy = cast<PointerType>(V->getType());
517 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
518 Instruction *User = cast<Instruction>(*UI);
520 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
521 if (MergeInType(LI->getType(), UsedType, TD))
524 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
525 // Storing the pointer, not into the value?
526 if (SI->getOperand(0) == V) return 0;
528 // NOTE: We could handle storing of FP imms into integers here!
530 if (MergeInType(SI->getOperand(0)->getType(), UsedType, TD))
532 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
534 const Type *SubTy = CanConvertToScalar(CI, IsNotTrivial);
535 if (!SubTy || MergeInType(SubTy, UsedType, TD)) return 0;
536 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
537 // Check to see if this is stepping over an element: GEP Ptr, int C
538 if (GEP->getNumOperands() == 2 && isa<ConstantInt>(GEP->getOperand(1))) {
539 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
540 unsigned ElSize = TD.getTypeSize(PTy->getElementType());
541 unsigned BitOffset = Idx*ElSize*8;
542 if (BitOffset > 64 || !isPowerOf2_32(ElSize)) return 0;
545 const Type *SubElt = CanConvertToScalar(GEP, IsNotTrivial);
546 if (SubElt == 0) return 0;
547 if (SubElt != Type::VoidTy && SubElt->isInteger()) {
549 getUIntAtLeastAsBitAs(TD.getTypeSize(SubElt)*8+BitOffset);
550 if (NewTy == 0 || MergeInType(NewTy, UsedType, TD)) return 0;
553 } else if (GEP->getNumOperands() == 3 &&
554 isa<ConstantInt>(GEP->getOperand(1)) &&
555 isa<ConstantInt>(GEP->getOperand(2)) &&
556 cast<Constant>(GEP->getOperand(1))->isNullValue()) {
557 // We are stepping into an element, e.g. a structure or an array:
558 // GEP Ptr, int 0, uint C
559 const Type *AggTy = PTy->getElementType();
560 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
562 if (const ArrayType *ATy = dyn_cast<ArrayType>(AggTy)) {
563 if (Idx >= ATy->getNumElements()) return 0; // Out of range.
564 } else if (const VectorType *VectorTy = dyn_cast<VectorType>(AggTy)) {
565 // Getting an element of the packed vector.
566 if (Idx >= VectorTy->getNumElements()) return 0; // Out of range.
568 // Merge in the vector type.
569 if (MergeInType(VectorTy, UsedType, TD)) return 0;
571 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
572 if (SubTy == 0) return 0;
574 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
577 // We'll need to change this to an insert/extract element operation.
579 continue; // Everything looks ok
581 } else if (isa<StructType>(AggTy)) {
582 // Structs are always ok.
586 const Type *NTy = getUIntAtLeastAsBitAs(TD.getTypeSize(AggTy)*8);
587 if (NTy == 0 || MergeInType(NTy, UsedType, TD)) return 0;
588 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
589 if (SubTy == 0) return 0;
590 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
592 continue; // Everything looks ok
596 // Cannot handle this!
604 /// ConvertToScalar - The specified alloca passes the CanConvertToScalar
605 /// predicate and is non-trivial. Convert it to something that can be trivially
606 /// promoted into a register by mem2reg.
607 void SROA::ConvertToScalar(AllocationInst *AI, const Type *ActualTy) {
608 DOUT << "CONVERT TO SCALAR: " << *AI << " TYPE = "
609 << *ActualTy << "\n";
612 BasicBlock *EntryBlock = AI->getParent();
613 assert(EntryBlock == &EntryBlock->getParent()->front() &&
614 "Not in the entry block!");
615 EntryBlock->getInstList().remove(AI); // Take the alloca out of the program.
617 // Create and insert the alloca.
618 AllocaInst *NewAI = new AllocaInst(ActualTy, 0, AI->getName(),
619 EntryBlock->begin());
620 ConvertUsesToScalar(AI, NewAI, 0);
625 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
626 /// directly. This happens when we are converting an "integer union" to a
627 /// single integer scalar, or when we are converting a "vector union" to a
628 /// vector with insert/extractelement instructions.
630 /// Offset is an offset from the original alloca, in bits that need to be
631 /// shifted to the right. By the end of this, there should be no uses of Ptr.
632 void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset) {
633 bool isVectorInsert = isa<VectorType>(NewAI->getType()->getElementType());
634 const TargetData &TD = getAnalysis<TargetData>();
635 while (!Ptr->use_empty()) {
636 Instruction *User = cast<Instruction>(Ptr->use_back());
638 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
639 // The load is a bit extract from NewAI shifted right by Offset bits.
640 Value *NV = new LoadInst(NewAI, LI->getName(), LI);
641 if (NV->getType() != LI->getType()) {
642 if (const VectorType *PTy = dyn_cast<VectorType>(NV->getType())) {
643 // If the result alloca is a vector type, this is either an element
644 // access or a bitcast to another vector type.
645 if (isa<VectorType>(LI->getType())) {
646 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
648 // Must be an element access.
649 unsigned Elt = Offset/(TD.getTypeSize(PTy->getElementType())*8);
650 NV = new ExtractElementInst(
651 NV, ConstantInt::get(Type::Int32Ty, Elt), "tmp", LI);
653 } else if (isa<PointerType>(NV->getType())) {
654 assert(isa<PointerType>(LI->getType()));
655 // Must be ptr->ptr cast. Anything else would result in NV being
657 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
659 assert(NV->getType()->isInteger() && "Unknown promotion!");
660 if (Offset && Offset < TD.getTypeSize(NV->getType())*8) {
661 NV = BinaryOperator::createLShr(NV,
662 ConstantInt::get(NV->getType(), Offset),
666 // If the result is an integer, this is a trunc or bitcast.
667 if (LI->getType()->isInteger()) {
668 NV = CastInst::createTruncOrBitCast(NV, LI->getType(),
670 } else if (LI->getType()->isFloatingPoint()) {
671 // If needed, truncate the integer to the appropriate size.
672 if (NV->getType()->getPrimitiveSizeInBits() >
673 LI->getType()->getPrimitiveSizeInBits()) {
674 switch (LI->getType()->getTypeID()) {
675 default: assert(0 && "Unknown FP type!");
676 case Type::FloatTyID:
677 NV = new TruncInst(NV, Type::Int32Ty, LI->getName(), LI);
679 case Type::DoubleTyID:
680 NV = new TruncInst(NV, Type::Int64Ty, LI->getName(), LI);
685 // Then do a bitcast.
686 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
688 // Otherwise must be a pointer.
689 NV = new IntToPtrInst(NV, LI->getType(), LI->getName(), LI);
693 LI->replaceAllUsesWith(NV);
694 LI->eraseFromParent();
695 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
696 assert(SI->getOperand(0) != Ptr && "Consistency error!");
698 // Convert the stored type to the actual type, shift it left to insert
699 // then 'or' into place.
700 Value *SV = SI->getOperand(0);
701 const Type *AllocaType = NewAI->getType()->getElementType();
702 if (SV->getType() != AllocaType) {
703 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
705 if (const VectorType *PTy = dyn_cast<VectorType>(AllocaType)) {
706 // If the result alloca is a vector type, this is either an element
707 // access or a bitcast to another vector type.
708 if (isa<VectorType>(SV->getType())) {
709 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
711 // Must be an element insertion.
712 unsigned Elt = Offset/(TD.getTypeSize(PTy->getElementType())*8);
713 SV = new InsertElementInst(Old, SV,
714 ConstantInt::get(Type::Int32Ty, Elt),
718 // If SV is a float, convert it to the appropriate integer type.
719 // If it is a pointer, do the same, and also handle ptr->ptr casts
721 switch (SV->getType()->getTypeID()) {
723 assert(!SV->getType()->isFloatingPoint() && "Unknown FP type!");
725 case Type::FloatTyID:
726 SV = new BitCastInst(SV, Type::Int32Ty, SV->getName(), SI);
728 case Type::DoubleTyID:
729 SV = new BitCastInst(SV, Type::Int64Ty, SV->getName(), SI);
731 case Type::PointerTyID:
732 if (isa<PointerType>(AllocaType))
733 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
735 SV = new PtrToIntInst(SV, TD.getIntPtrType(), SV->getName(), SI);
739 unsigned SrcSize = TD.getTypeSize(SV->getType())*8;
741 // Always zero extend the value if needed.
742 if (SV->getType() != AllocaType)
743 SV = CastInst::createZExtOrBitCast(SV, AllocaType,
745 if (Offset && Offset < AllocaType->getPrimitiveSizeInBits())
746 SV = BinaryOperator::createShl(SV,
747 ConstantInt::get(SV->getType(), Offset),
748 SV->getName()+".adj", SI);
749 // Mask out the bits we are about to insert from the old value.
750 unsigned TotalBits = TD.getTypeSize(SV->getType())*8;
751 if (TotalBits != SrcSize) {
752 assert(TotalBits > SrcSize);
753 uint64_t Mask = ~(((1ULL << SrcSize)-1) << Offset);
754 Mask = Mask & cast<IntegerType>(SV->getType())->getBitMask();
755 Old = BinaryOperator::createAnd(Old,
756 ConstantInt::get(Old->getType(), Mask),
757 Old->getName()+".mask", SI);
758 SV = BinaryOperator::createOr(Old, SV, SV->getName()+".ins", SI);
762 new StoreInst(SV, NewAI, SI);
763 SI->eraseFromParent();
765 } else if (CastInst *CI = dyn_cast<CastInst>(User)) {
766 unsigned NewOff = Offset;
767 const TargetData &TD = getAnalysis<TargetData>();
768 if (TD.isBigEndian() && !isVectorInsert) {
769 // Adjust the pointer. For example, storing 16-bits into a 32-bit
770 // alloca with just a cast makes it modify the top 16-bits.
771 const Type *SrcTy = cast<PointerType>(Ptr->getType())->getElementType();
772 const Type *DstTy = cast<PointerType>(CI->getType())->getElementType();
773 int PtrDiffBits = TD.getTypeSize(SrcTy)*8-TD.getTypeSize(DstTy)*8;
774 NewOff += PtrDiffBits;
776 ConvertUsesToScalar(CI, NewAI, NewOff);
777 CI->eraseFromParent();
778 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
779 const PointerType *AggPtrTy =
780 cast<PointerType>(GEP->getOperand(0)->getType());
781 const TargetData &TD = getAnalysis<TargetData>();
782 unsigned AggSizeInBits = TD.getTypeSize(AggPtrTy->getElementType())*8;
784 // Check to see if this is stepping over an element: GEP Ptr, int C
785 unsigned NewOffset = Offset;
786 if (GEP->getNumOperands() == 2) {
787 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
788 unsigned BitOffset = Idx*AggSizeInBits;
790 if (TD.isLittleEndian() || isVectorInsert)
791 NewOffset += BitOffset;
793 NewOffset -= BitOffset;
795 } else if (GEP->getNumOperands() == 3) {
796 // We know that operand #2 is zero.
797 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
798 const Type *AggTy = AggPtrTy->getElementType();
799 if (const SequentialType *SeqTy = dyn_cast<SequentialType>(AggTy)) {
800 unsigned ElSizeBits = TD.getTypeSize(SeqTy->getElementType())*8;
802 if (TD.isLittleEndian() || isVectorInsert)
803 NewOffset += ElSizeBits*Idx;
805 NewOffset += AggSizeInBits-ElSizeBits*(Idx+1);
806 } else if (const StructType *STy = dyn_cast<StructType>(AggTy)) {
807 unsigned EltBitOffset =
808 TD.getStructLayout(STy)->getElementOffset(Idx)*8;
810 if (TD.isLittleEndian() || isVectorInsert)
811 NewOffset += EltBitOffset;
813 const PointerType *ElPtrTy = cast<PointerType>(GEP->getType());
814 unsigned ElSizeBits = TD.getTypeSize(ElPtrTy->getElementType())*8;
815 NewOffset += AggSizeInBits-(EltBitOffset+ElSizeBits);
819 assert(0 && "Unsupported operation!");
823 assert(0 && "Unsupported operation!");
826 ConvertUsesToScalar(GEP, NewAI, NewOffset);
827 GEP->eraseFromParent();
829 assert(0 && "Unsupported operation!");