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/Support/Debug.h"
35 #include "llvm/Support/GetElementPtrTypeIterator.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Compiler.h"
38 #include "llvm/ADT/SmallVector.h"
39 #include "llvm/ADT/Statistic.h"
40 #include "llvm/ADT/StringExtras.h"
43 STATISTIC(NumReplaced, "Number of allocas broken up");
44 STATISTIC(NumPromoted, "Number of allocas promoted");
45 STATISTIC(NumConverted, "Number of aggregates converted to scalar");
46 STATISTIC(NumGlobals, "Number of allocas copied from constant global");
49 struct VISIBILITY_HIDDEN SROA : public FunctionPass {
50 static char ID; // Pass identification, replacement for typeid
51 explicit SROA(signed T = -1) : FunctionPass(&ID) {
58 bool runOnFunction(Function &F);
60 bool performScalarRepl(Function &F);
61 bool performPromotion(Function &F);
63 // getAnalysisUsage - This pass does not require any passes, but we know it
64 // will not alter the CFG, so say so.
65 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
66 AU.addRequired<DominatorTree>();
67 AU.addRequired<DominanceFrontier>();
68 AU.addRequired<TargetData>();
75 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
76 /// information about the uses. All these fields are initialized to false
77 /// and set to true when something is learned.
79 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
82 /// needsCanon - This is set to true if there is some use of the alloca
83 /// that requires canonicalization.
86 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
89 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
93 : isUnsafe(false), needsCanon(false),
94 isMemCpySrc(false), isMemCpyDst(false) {}
99 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
101 int isSafeAllocaToScalarRepl(AllocationInst *AI);
103 void isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
105 void isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
107 void isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
108 unsigned OpNo, AllocaInfo &Info);
109 void isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI,
112 void DoScalarReplacement(AllocationInst *AI,
113 std::vector<AllocationInst*> &WorkList);
114 void CanonicalizeAllocaUsers(AllocationInst *AI);
115 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
117 void RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
118 SmallVector<AllocaInst*, 32> &NewElts);
120 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
122 SmallVector<AllocaInst*, 32> &NewElts);
123 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocationInst *AI,
124 SmallVector<AllocaInst*, 32> &NewElts);
125 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
126 SmallVector<AllocaInst*, 32> &NewElts);
128 const Type *CanConvertToScalar(Value *V, bool &IsNotTrivial);
129 void ConvertToScalar(AllocationInst *AI, const Type *Ty);
130 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset);
131 Value *ConvertUsesOfLoadToScalar(LoadInst *LI, AllocaInst *NewAI,
133 Value *ConvertUsesOfStoreToScalar(StoreInst *SI, AllocaInst *NewAI,
135 static Instruction *isOnlyCopiedFromConstantGlobal(AllocationInst *AI);
140 static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
142 // Public interface to the ScalarReplAggregates pass
143 FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
144 return new SROA(Threshold);
148 bool SROA::runOnFunction(Function &F) {
149 TD = &getAnalysis<TargetData>();
151 bool Changed = performPromotion(F);
153 bool LocalChange = performScalarRepl(F);
154 if (!LocalChange) break; // No need to repromote if no scalarrepl
156 LocalChange = performPromotion(F);
157 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
164 bool SROA::performPromotion(Function &F) {
165 std::vector<AllocaInst*> Allocas;
166 DominatorTree &DT = getAnalysis<DominatorTree>();
167 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
169 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
171 bool Changed = false;
176 // Find allocas that are safe to promote, by looking at all instructions in
178 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
179 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
180 if (isAllocaPromotable(AI))
181 Allocas.push_back(AI);
183 if (Allocas.empty()) break;
185 PromoteMemToReg(Allocas, DT, DF);
186 NumPromoted += Allocas.size();
193 /// getNumSAElements - Return the number of elements in the specific struct or
195 static uint64_t getNumSAElements(const Type *T) {
196 if (const StructType *ST = dyn_cast<StructType>(T))
197 return ST->getNumElements();
198 return cast<ArrayType>(T)->getNumElements();
201 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
202 // which runs on all of the malloc/alloca instructions in the function, removing
203 // them if they are only used by getelementptr instructions.
205 bool SROA::performScalarRepl(Function &F) {
206 std::vector<AllocationInst*> WorkList;
208 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
209 BasicBlock &BB = F.getEntryBlock();
210 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
211 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
212 WorkList.push_back(A);
214 // Process the worklist
215 bool Changed = false;
216 while (!WorkList.empty()) {
217 AllocationInst *AI = WorkList.back();
220 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
221 // with unused elements.
222 if (AI->use_empty()) {
223 AI->eraseFromParent();
227 // If we can turn this aggregate value (potentially with casts) into a
228 // simple scalar value that can be mem2reg'd into a register value.
229 bool IsNotTrivial = false;
230 if (const Type *ActualType = CanConvertToScalar(AI, IsNotTrivial))
231 if (IsNotTrivial && ActualType != Type::VoidTy) {
232 ConvertToScalar(AI, ActualType);
237 // Check to see if we can perform the core SROA transformation. We cannot
238 // transform the allocation instruction if it is an array allocation
239 // (allocations OF arrays are ok though), and an allocation of a scalar
240 // value cannot be decomposed at all.
241 if (!AI->isArrayAllocation() &&
242 (isa<StructType>(AI->getAllocatedType()) ||
243 isa<ArrayType>(AI->getAllocatedType())) &&
244 AI->getAllocatedType()->isSized() &&
245 // Do not promote any struct whose size is larger than "128" bytes.
246 TD->getABITypeSize(AI->getAllocatedType()) < SRThreshold &&
247 // Do not promote any struct into more than "32" separate vars.
248 getNumSAElements(AI->getAllocatedType()) < SRThreshold/4) {
249 // Check that all of the users of the allocation are capable of being
251 switch (isSafeAllocaToScalarRepl(AI)) {
252 default: assert(0 && "Unexpected value!");
253 case 0: // Not safe to scalar replace.
255 case 1: // Safe, but requires cleanup/canonicalizations first
256 CanonicalizeAllocaUsers(AI);
258 case 3: // Safe to scalar replace.
259 DoScalarReplacement(AI, WorkList);
265 // Check to see if this allocation is only modified by a memcpy/memmove from
266 // a constant global. If this is the case, we can change all users to use
267 // the constant global instead. This is commonly produced by the CFE by
268 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
269 // is only subsequently read.
270 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
271 DOUT << "Found alloca equal to global: " << *AI;
272 DOUT << " memcpy = " << *TheCopy;
273 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
274 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
275 TheCopy->eraseFromParent(); // Don't mutate the global.
276 AI->eraseFromParent();
282 // Otherwise, couldn't process this.
288 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
289 /// predicate, do SROA now.
290 void SROA::DoScalarReplacement(AllocationInst *AI,
291 std::vector<AllocationInst*> &WorkList) {
292 DOUT << "Found inst to SROA: " << *AI;
293 SmallVector<AllocaInst*, 32> ElementAllocas;
294 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
295 ElementAllocas.reserve(ST->getNumContainedTypes());
296 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
297 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
299 AI->getName() + "." + utostr(i), AI);
300 ElementAllocas.push_back(NA);
301 WorkList.push_back(NA); // Add to worklist for recursive processing
304 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
305 ElementAllocas.reserve(AT->getNumElements());
306 const Type *ElTy = AT->getElementType();
307 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
308 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
309 AI->getName() + "." + utostr(i), AI);
310 ElementAllocas.push_back(NA);
311 WorkList.push_back(NA); // Add to worklist for recursive processing
315 // Now that we have created the alloca instructions that we want to use,
316 // expand the getelementptr instructions to use them.
318 while (!AI->use_empty()) {
319 Instruction *User = cast<Instruction>(AI->use_back());
320 if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
321 RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
322 BCInst->eraseFromParent();
327 // %res = load { i32, i32 }* %alloc
329 // %load.0 = load i32* %alloc.0
330 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
331 // %load.1 = load i32* %alloc.1
332 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
333 // (Also works for arrays instead of structs)
334 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
335 Value *Insert = UndefValue::get(LI->getType());
336 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
337 Value *Load = new LoadInst(ElementAllocas[i], "load", LI);
338 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
340 LI->replaceAllUsesWith(Insert);
341 LI->eraseFromParent();
346 // store { i32, i32 } %val, { i32, i32 }* %alloc
348 // %val.0 = extractvalue { i32, i32 } %val, 0
349 // store i32 %val.0, i32* %alloc.0
350 // %val.1 = extractvalue { i32, i32 } %val, 1
351 // store i32 %val.1, i32* %alloc.1
352 // (Also works for arrays instead of structs)
353 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
354 Value *Val = SI->getOperand(0);
355 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
356 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
357 new StoreInst(Extract, ElementAllocas[i], SI);
359 SI->eraseFromParent();
363 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
364 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
366 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
368 assert(Idx < ElementAllocas.size() && "Index out of range?");
369 AllocaInst *AllocaToUse = ElementAllocas[Idx];
372 if (GEPI->getNumOperands() == 3) {
373 // Do not insert a new getelementptr instruction with zero indices, only
374 // to have it optimized out later.
375 RepValue = AllocaToUse;
377 // We are indexing deeply into the structure, so we still need a
378 // getelement ptr instruction to finish the indexing. This may be
379 // expanded itself once the worklist is rerun.
381 SmallVector<Value*, 8> NewArgs;
382 NewArgs.push_back(Constant::getNullValue(Type::Int32Ty));
383 NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
384 RepValue = GetElementPtrInst::Create(AllocaToUse, NewArgs.begin(),
385 NewArgs.end(), "", GEPI);
386 RepValue->takeName(GEPI);
389 // If this GEP is to the start of the aggregate, check for memcpys.
390 if (Idx == 0 && GEPI->hasAllZeroIndices())
391 RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas);
393 // Move all of the users over to the new GEP.
394 GEPI->replaceAllUsesWith(RepValue);
395 // Delete the old GEP
396 GEPI->eraseFromParent();
399 // Finally, delete the Alloca instruction
400 AI->eraseFromParent();
405 /// isSafeElementUse - Check to see if this use is an allowed use for a
406 /// getelementptr instruction of an array aggregate allocation. isFirstElt
407 /// indicates whether Ptr is known to the start of the aggregate.
409 void SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
411 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
413 Instruction *User = cast<Instruction>(*I);
414 switch (User->getOpcode()) {
415 case Instruction::Load: break;
416 case Instruction::Store:
417 // Store is ok if storing INTO the pointer, not storing the pointer
418 if (User->getOperand(0) == Ptr) return MarkUnsafe(Info);
420 case Instruction::GetElementPtr: {
421 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
422 bool AreAllZeroIndices = isFirstElt;
423 if (GEP->getNumOperands() > 1) {
424 if (!isa<ConstantInt>(GEP->getOperand(1)) ||
425 !cast<ConstantInt>(GEP->getOperand(1))->isZero())
426 // Using pointer arithmetic to navigate the array.
427 return MarkUnsafe(Info);
429 if (AreAllZeroIndices)
430 AreAllZeroIndices = GEP->hasAllZeroIndices();
432 isSafeElementUse(GEP, AreAllZeroIndices, AI, Info);
433 if (Info.isUnsafe) return;
436 case Instruction::BitCast:
438 isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI, Info);
439 if (Info.isUnsafe) return;
442 DOUT << " Transformation preventing inst: " << *User;
443 return MarkUnsafe(Info);
444 case Instruction::Call:
445 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
447 isSafeMemIntrinsicOnAllocation(MI, AI, I.getOperandNo(), Info);
448 if (Info.isUnsafe) return;
452 DOUT << " Transformation preventing inst: " << *User;
453 return MarkUnsafe(Info);
455 DOUT << " Transformation preventing inst: " << *User;
456 return MarkUnsafe(Info);
459 return; // All users look ok :)
462 /// AllUsersAreLoads - Return true if all users of this value are loads.
463 static bool AllUsersAreLoads(Value *Ptr) {
464 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
466 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
471 /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
472 /// aggregate allocation.
474 void SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
476 if (BitCastInst *C = dyn_cast<BitCastInst>(User))
477 return isSafeUseOfBitCastedAllocation(C, AI, Info);
479 if (isa<LoadInst>(User))
480 return; // Loads (returning a first class aggregrate) are always rewritable
482 if (isa<StoreInst>(User) && User->getOperand(0) != AI)
483 return; // Store is ok if storing INTO the pointer, not storing the pointer
485 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User);
487 return MarkUnsafe(Info);
489 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
491 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
493 I.getOperand() != Constant::getNullValue(I.getOperand()->getType())) {
494 return MarkUnsafe(Info);
498 if (I == E) return MarkUnsafe(Info); // ran out of GEP indices??
500 bool IsAllZeroIndices = true;
502 // If the first index is a non-constant index into an array, see if we can
503 // handle it as a special case.
504 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
505 if (!isa<ConstantInt>(I.getOperand())) {
506 IsAllZeroIndices = 0;
507 uint64_t NumElements = AT->getNumElements();
509 // If this is an array index and the index is not constant, we cannot
510 // promote... that is unless the array has exactly one or two elements in
511 // it, in which case we CAN promote it, but we have to canonicalize this
512 // out if this is the only problem.
513 if ((NumElements == 1 || NumElements == 2) &&
514 AllUsersAreLoads(GEPI)) {
515 Info.needsCanon = true;
516 return; // Canonicalization required!
518 return MarkUnsafe(Info);
522 // Walk through the GEP type indices, checking the types that this indexes
524 for (; I != E; ++I) {
525 // Ignore struct elements, no extra checking needed for these.
526 if (isa<StructType>(*I))
529 ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
530 if (!IdxVal) return MarkUnsafe(Info);
532 // Are all indices still zero?
533 IsAllZeroIndices &= IdxVal->isZero();
535 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
536 // This GEP indexes an array. Verify that this is an in-range constant
537 // integer. Specifically, consider A[0][i]. We cannot know that the user
538 // isn't doing invalid things like allowing i to index an out-of-range
539 // subscript that accesses A[1]. Because of this, we have to reject SROA
540 // of any accesses into structs where any of the components are variables.
541 if (IdxVal->getZExtValue() >= AT->getNumElements())
542 return MarkUnsafe(Info);
543 } else if (const VectorType *VT = dyn_cast<VectorType>(*I)) {
544 if (IdxVal->getZExtValue() >= VT->getNumElements())
545 return MarkUnsafe(Info);
549 // If there are any non-simple uses of this getelementptr, make sure to reject
551 return isSafeElementUse(GEPI, IsAllZeroIndices, AI, Info);
554 /// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
555 /// intrinsic can be promoted by SROA. At this point, we know that the operand
556 /// of the memintrinsic is a pointer to the beginning of the allocation.
557 void SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
558 unsigned OpNo, AllocaInfo &Info) {
559 // If not constant length, give up.
560 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
561 if (!Length) return MarkUnsafe(Info);
563 // If not the whole aggregate, give up.
564 if (Length->getZExtValue() !=
565 TD->getABITypeSize(AI->getType()->getElementType()))
566 return MarkUnsafe(Info);
568 // We only know about memcpy/memset/memmove.
569 if (!isa<MemCpyInst>(MI) && !isa<MemSetInst>(MI) && !isa<MemMoveInst>(MI))
570 return MarkUnsafe(Info);
572 // Otherwise, we can transform it. Determine whether this is a memcpy/set
573 // into or out of the aggregate.
575 Info.isMemCpyDst = true;
578 Info.isMemCpySrc = true;
582 /// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
584 void SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI,
586 for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
588 if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
589 isSafeUseOfBitCastedAllocation(BCU, AI, Info);
590 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
591 isSafeMemIntrinsicOnAllocation(MI, AI, UI.getOperandNo(), Info);
592 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
593 // If storing the entire alloca in one chunk through a bitcasted pointer
594 // to integer, we can transform it. This happens (for example) when you
595 // cast a {i32,i32}* to i64* and store through it. This is similar to the
596 // memcpy case and occurs in various "byval" cases and emulated memcpys.
597 if (isa<IntegerType>(SI->getOperand(0)->getType()) &&
598 TD->getABITypeSize(SI->getOperand(0)->getType()) ==
599 TD->getABITypeSize(AI->getType()->getElementType())) {
600 Info.isMemCpyDst = true;
603 return MarkUnsafe(Info);
604 } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
605 // If loading the entire alloca in one chunk through a bitcasted pointer
606 // to integer, we can transform it. This happens (for example) when you
607 // cast a {i32,i32}* to i64* and load through it. This is similar to the
608 // memcpy case and occurs in various "byval" cases and emulated memcpys.
609 if (isa<IntegerType>(LI->getType()) &&
610 TD->getABITypeSize(LI->getType()) ==
611 TD->getABITypeSize(AI->getType()->getElementType())) {
612 Info.isMemCpySrc = true;
615 return MarkUnsafe(Info);
617 return MarkUnsafe(Info);
619 if (Info.isUnsafe) return;
623 /// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
624 /// to its first element. Transform users of the cast to use the new values
626 void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
627 SmallVector<AllocaInst*, 32> &NewElts) {
628 Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
630 Instruction *User = cast<Instruction>(*UI++);
631 if (BitCastInst *BCU = dyn_cast<BitCastInst>(User)) {
632 RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
633 if (BCU->use_empty()) BCU->eraseFromParent();
637 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
638 // This must be memcpy/memmove/memset of the entire aggregate.
639 // Split into one per element.
640 RewriteMemIntrinUserOfAlloca(MI, BCInst, AI, NewElts);
644 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
645 // If this is a store of the entire alloca from an integer, rewrite it.
646 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
650 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
651 // If this is a load of the entire alloca to an integer, rewrite it.
652 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
656 // Otherwise it must be some other user of a gep of the first pointer. Just
657 // leave these alone.
662 /// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
663 /// Rewrite it to copy or set the elements of the scalarized memory.
664 void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
666 SmallVector<AllocaInst*, 32> &NewElts) {
668 // If this is a memcpy/memmove, construct the other pointer as the
671 if (MemCpyInst *MCI = dyn_cast<MemCpyInst>(MI)) {
672 if (BCInst == MCI->getRawDest())
673 OtherPtr = MCI->getRawSource();
675 assert(BCInst == MCI->getRawSource());
676 OtherPtr = MCI->getRawDest();
678 } else if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
679 if (BCInst == MMI->getRawDest())
680 OtherPtr = MMI->getRawSource();
682 assert(BCInst == MMI->getRawSource());
683 OtherPtr = MMI->getRawDest();
687 // If there is an other pointer, we want to convert it to the same pointer
688 // type as AI has, so we can GEP through it safely.
690 // It is likely that OtherPtr is a bitcast, if so, remove it.
691 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
692 OtherPtr = BC->getOperand(0);
693 // All zero GEPs are effectively bitcasts.
694 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr))
695 if (GEP->hasAllZeroIndices())
696 OtherPtr = GEP->getOperand(0);
698 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
699 if (BCE->getOpcode() == Instruction::BitCast)
700 OtherPtr = BCE->getOperand(0);
702 // If the pointer is not the right type, insert a bitcast to the right
704 if (OtherPtr->getType() != AI->getType())
705 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
709 // Process each element of the aggregate.
710 Value *TheFn = MI->getOperand(0);
711 const Type *BytePtrTy = MI->getRawDest()->getType();
712 bool SROADest = MI->getRawDest() == BCInst;
714 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
716 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
717 // If this is a memcpy/memmove, emit a GEP of the other element address.
720 Value *Idx[2] = { Zero, ConstantInt::get(Type::Int32Ty, i) };
721 OtherElt = GetElementPtrInst::Create(OtherPtr, Idx, Idx + 2,
722 OtherPtr->getNameStr()+"."+utostr(i),
726 Value *EltPtr = NewElts[i];
727 const Type *EltTy =cast<PointerType>(EltPtr->getType())->getElementType();
729 // If we got down to a scalar, insert a load or store as appropriate.
730 if (EltTy->isSingleValueType()) {
731 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
732 Value *Elt = new LoadInst(SROADest ? OtherElt : EltPtr, "tmp",
734 new StoreInst(Elt, SROADest ? EltPtr : OtherElt, MI);
737 assert(isa<MemSetInst>(MI));
739 // If the stored element is zero (common case), just store a null
742 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
744 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
746 // If EltTy is a vector type, get the element type.
747 const Type *ValTy = EltTy;
748 if (const VectorType *VTy = dyn_cast<VectorType>(ValTy))
749 ValTy = VTy->getElementType();
751 // Construct an integer with the right value.
752 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
753 APInt OneVal(EltSize, CI->getZExtValue());
754 APInt TotalVal(OneVal);
756 for (unsigned i = 0; 8*i < EltSize; ++i) {
757 TotalVal = TotalVal.shl(8);
761 // Convert the integer value to the appropriate type.
762 StoreVal = ConstantInt::get(TotalVal);
763 if (isa<PointerType>(ValTy))
764 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
765 else if (ValTy->isFloatingPoint())
766 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
767 assert(StoreVal->getType() == ValTy && "Type mismatch!");
769 // If the requested value was a vector constant, create it.
770 if (EltTy != ValTy) {
771 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
772 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
773 StoreVal = ConstantVector::get(&Elts[0], NumElts);
776 new StoreInst(StoreVal, EltPtr, MI);
779 // Otherwise, if we're storing a byte variable, use a memset call for
783 // Cast the element pointer to BytePtrTy.
784 if (EltPtr->getType() != BytePtrTy)
785 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
787 // Cast the other pointer (if we have one) to BytePtrTy.
788 if (OtherElt && OtherElt->getType() != BytePtrTy)
789 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
792 unsigned EltSize = TD->getABITypeSize(EltTy);
794 // Finally, insert the meminst for this element.
795 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
797 SROADest ? EltPtr : OtherElt, // Dest ptr
798 SROADest ? OtherElt : EltPtr, // Src ptr
799 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
802 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
804 assert(isa<MemSetInst>(MI));
806 EltPtr, MI->getOperand(2), // Dest, Value,
807 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
810 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
813 MI->eraseFromParent();
816 /// RewriteStoreUserOfWholeAlloca - We found an store of an integer that
817 /// overwrites the entire allocation. Extract out the pieces of the stored
818 /// integer and store them individually.
819 void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI,
821 SmallVector<AllocaInst*, 32> &NewElts){
822 // Extract each element out of the integer according to its structure offset
823 // and store the element value to the individual alloca.
824 Value *SrcVal = SI->getOperand(0);
825 const Type *AllocaEltTy = AI->getType()->getElementType();
826 uint64_t AllocaSizeBits = TD->getABITypeSizeInBits(AllocaEltTy);
828 // If this isn't a store of an integer to the whole alloca, it may be a store
829 // to the first element. Just ignore the store in this case and normal SROA
831 if (!isa<IntegerType>(SrcVal->getType()) ||
832 TD->getABITypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
835 DOUT << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << *SI;
837 // There are two forms here: AI could be an array or struct. Both cases
838 // have different ways to compute the element offset.
839 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
840 const StructLayout *Layout = TD->getStructLayout(EltSTy);
842 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
843 // Get the number of bits to shift SrcVal to get the value.
844 const Type *FieldTy = EltSTy->getElementType(i);
845 uint64_t Shift = Layout->getElementOffsetInBits(i);
847 if (TD->isBigEndian())
848 Shift = AllocaSizeBits-Shift-TD->getABITypeSizeInBits(FieldTy);
850 Value *EltVal = SrcVal;
852 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
853 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
854 "sroa.store.elt", SI);
857 // Truncate down to an integer of the right size.
858 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
860 // Ignore zero sized fields like {}, they obviously contain no data.
861 if (FieldSizeBits == 0) continue;
863 if (FieldSizeBits != AllocaSizeBits)
864 EltVal = new TruncInst(EltVal, IntegerType::get(FieldSizeBits), "", SI);
865 Value *DestField = NewElts[i];
866 if (EltVal->getType() == FieldTy) {
867 // Storing to an integer field of this size, just do it.
868 } else if (FieldTy->isFloatingPoint() || isa<VectorType>(FieldTy)) {
869 // Bitcast to the right element type (for fp/vector values).
870 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
872 // Otherwise, bitcast the dest pointer (for aggregates).
873 DestField = new BitCastInst(DestField,
874 PointerType::getUnqual(EltVal->getType()),
877 new StoreInst(EltVal, DestField, SI);
881 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
882 const Type *ArrayEltTy = ATy->getElementType();
883 uint64_t ElementOffset = TD->getABITypeSizeInBits(ArrayEltTy);
884 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
888 if (TD->isBigEndian())
889 Shift = AllocaSizeBits-ElementOffset;
893 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
894 // Ignore zero sized fields like {}, they obviously contain no data.
895 if (ElementSizeBits == 0) continue;
897 Value *EltVal = SrcVal;
899 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
900 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
901 "sroa.store.elt", SI);
904 // Truncate down to an integer of the right size.
905 if (ElementSizeBits != AllocaSizeBits)
906 EltVal = new TruncInst(EltVal, IntegerType::get(ElementSizeBits),"",SI);
907 Value *DestField = NewElts[i];
908 if (EltVal->getType() == ArrayEltTy) {
909 // Storing to an integer field of this size, just do it.
910 } else if (ArrayEltTy->isFloatingPoint() || isa<VectorType>(ArrayEltTy)) {
911 // Bitcast to the right element type (for fp/vector values).
912 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
914 // Otherwise, bitcast the dest pointer (for aggregates).
915 DestField = new BitCastInst(DestField,
916 PointerType::getUnqual(EltVal->getType()),
919 new StoreInst(EltVal, DestField, SI);
921 if (TD->isBigEndian())
922 Shift -= ElementOffset;
924 Shift += ElementOffset;
928 SI->eraseFromParent();
931 /// RewriteLoadUserOfWholeAlloca - We found an load of the entire allocation to
932 /// an integer. Load the individual pieces to form the aggregate value.
933 void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
934 SmallVector<AllocaInst*, 32> &NewElts) {
935 // Extract each element out of the NewElts according to its structure offset
936 // and form the result value.
937 const Type *AllocaEltTy = AI->getType()->getElementType();
938 uint64_t AllocaSizeBits = TD->getABITypeSizeInBits(AllocaEltTy);
940 // If this isn't a load of the whole alloca to an integer, it may be a load
941 // of the first element. Just ignore the load in this case and normal SROA
943 if (!isa<IntegerType>(LI->getType()) ||
944 TD->getABITypeSizeInBits(LI->getType()) != AllocaSizeBits)
947 DOUT << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << *LI;
949 // There are two forms here: AI could be an array or struct. Both cases
950 // have different ways to compute the element offset.
951 const StructLayout *Layout = 0;
952 uint64_t ArrayEltBitOffset = 0;
953 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
954 Layout = TD->getStructLayout(EltSTy);
956 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
957 ArrayEltBitOffset = TD->getABITypeSizeInBits(ArrayEltTy);
960 Value *ResultVal = Constant::getNullValue(LI->getType());
962 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
963 // Load the value from the alloca. If the NewElt is an aggregate, cast
964 // the pointer to an integer of the same size before doing the load.
965 Value *SrcField = NewElts[i];
966 const Type *FieldTy =
967 cast<PointerType>(SrcField->getType())->getElementType();
968 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
970 // Ignore zero sized fields like {}, they obviously contain no data.
971 if (FieldSizeBits == 0) continue;
973 const IntegerType *FieldIntTy = IntegerType::get(FieldSizeBits);
974 if (!isa<IntegerType>(FieldTy) && !FieldTy->isFloatingPoint() &&
975 !isa<VectorType>(FieldTy))
976 SrcField = new BitCastInst(SrcField, PointerType::getUnqual(FieldIntTy),
978 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
980 // If SrcField is a fp or vector of the right size but that isn't an
981 // integer type, bitcast to an integer so we can shift it.
982 if (SrcField->getType() != FieldIntTy)
983 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
985 // Zero extend the field to be the same size as the final alloca so that
986 // we can shift and insert it.
987 if (SrcField->getType() != ResultVal->getType())
988 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
990 // Determine the number of bits to shift SrcField.
992 if (Layout) // Struct case.
993 Shift = Layout->getElementOffsetInBits(i);
995 Shift = i*ArrayEltBitOffset;
997 if (TD->isBigEndian())
998 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1001 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
1002 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1005 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1008 LI->replaceAllUsesWith(ResultVal);
1009 LI->eraseFromParent();
1013 /// HasPadding - Return true if the specified type has any structure or
1014 /// alignment padding, false otherwise.
1015 static bool HasPadding(const Type *Ty, const TargetData &TD) {
1016 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1017 const StructLayout *SL = TD.getStructLayout(STy);
1018 unsigned PrevFieldBitOffset = 0;
1019 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1020 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1022 // Padding in sub-elements?
1023 if (HasPadding(STy->getElementType(i), TD))
1026 // Check to see if there is any padding between this element and the
1029 unsigned PrevFieldEnd =
1030 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1031 if (PrevFieldEnd < FieldBitOffset)
1035 PrevFieldBitOffset = FieldBitOffset;
1038 // Check for tail padding.
1039 if (unsigned EltCount = STy->getNumElements()) {
1040 unsigned PrevFieldEnd = PrevFieldBitOffset +
1041 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
1042 if (PrevFieldEnd < SL->getSizeInBits())
1046 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1047 return HasPadding(ATy->getElementType(), TD);
1048 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1049 return HasPadding(VTy->getElementType(), TD);
1051 return TD.getTypeSizeInBits(Ty) != TD.getABITypeSizeInBits(Ty);
1054 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1055 /// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1056 /// or 1 if safe after canonicalization has been performed.
1058 int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
1059 // Loop over the use list of the alloca. We can only transform it if all of
1060 // the users are safe to transform.
1063 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
1065 isSafeUseOfAllocation(cast<Instruction>(*I), AI, Info);
1066 if (Info.isUnsafe) {
1067 DOUT << "Cannot transform: " << *AI << " due to user: " << **I;
1072 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1073 // source and destination, we have to be careful. In particular, the memcpy
1074 // could be moving around elements that live in structure padding of the LLVM
1075 // types, but may actually be used. In these cases, we refuse to promote the
1077 if (Info.isMemCpySrc && Info.isMemCpyDst &&
1078 HasPadding(AI->getType()->getElementType(), *TD))
1081 // If we require cleanup, return 1, otherwise return 3.
1082 return Info.needsCanon ? 1 : 3;
1085 /// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified
1086 /// allocation, but only if cleaned up, perform the cleanups required.
1087 void SROA::CanonicalizeAllocaUsers(AllocationInst *AI) {
1088 // At this point, we know that the end result will be SROA'd and promoted, so
1089 // we can insert ugly code if required so long as sroa+mem2reg will clean it
1091 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1093 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI++);
1094 if (!GEPI) continue;
1095 gep_type_iterator I = gep_type_begin(GEPI);
1098 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
1099 uint64_t NumElements = AT->getNumElements();
1101 if (!isa<ConstantInt>(I.getOperand())) {
1102 if (NumElements == 1) {
1103 GEPI->setOperand(2, Constant::getNullValue(Type::Int32Ty));
1105 assert(NumElements == 2 && "Unhandled case!");
1106 // All users of the GEP must be loads. At each use of the GEP, insert
1107 // two loads of the appropriate indexed GEP and select between them.
1108 Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(),
1109 Constant::getNullValue(I.getOperand()->getType()),
1111 // Insert the new GEP instructions, which are properly indexed.
1112 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
1113 Indices[1] = Constant::getNullValue(Type::Int32Ty);
1114 Value *ZeroIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1117 GEPI->getName()+".0", GEPI);
1118 Indices[1] = ConstantInt::get(Type::Int32Ty, 1);
1119 Value *OneIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1122 GEPI->getName()+".1", GEPI);
1123 // Replace all loads of the variable index GEP with loads from both
1124 // indexes and a select.
1125 while (!GEPI->use_empty()) {
1126 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
1127 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
1128 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
1129 Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI);
1130 LI->replaceAllUsesWith(R);
1131 LI->eraseFromParent();
1133 GEPI->eraseFromParent();
1140 /// MergeInType - Add the 'In' type to the accumulated type so far. If the
1141 /// types are incompatible, return true, otherwise update Accum and return
1144 /// There are three cases we handle here:
1145 /// 1) An effectively-integer union, where the pieces are stored into as
1146 /// smaller integers (common with byte swap and other idioms).
1147 /// 2) A union of vector types of the same size and potentially its elements.
1148 /// Here we turn element accesses into insert/extract element operations.
1149 /// 3) A union of scalar types, such as int/float or int/pointer. Here we
1150 /// merge together into integers, allowing the xform to work with #1 as
1152 static bool MergeInType(const Type *In, const Type *&Accum,
1153 const TargetData &TD) {
1154 // If this is our first type, just use it.
1155 const VectorType *PTy;
1156 if (Accum == Type::VoidTy || In == Accum) {
1158 } else if (In == Type::VoidTy) {
1160 } else if (In->isInteger() && Accum->isInteger()) { // integer union.
1161 // Otherwise pick whichever type is larger.
1162 if (cast<IntegerType>(In)->getBitWidth() >
1163 cast<IntegerType>(Accum)->getBitWidth())
1165 } else if (isa<PointerType>(In) && isa<PointerType>(Accum)) {
1166 // Pointer unions just stay as one of the pointers.
1167 } else if (isa<VectorType>(In) || isa<VectorType>(Accum)) {
1168 if ((PTy = dyn_cast<VectorType>(Accum)) &&
1169 PTy->getElementType() == In) {
1170 // Accum is a vector, and we are accessing an element: ok.
1171 } else if ((PTy = dyn_cast<VectorType>(In)) &&
1172 PTy->getElementType() == Accum) {
1173 // In is a vector, and accum is an element: ok, remember In.
1175 } else if ((PTy = dyn_cast<VectorType>(In)) && isa<VectorType>(Accum) &&
1176 PTy->getBitWidth() == cast<VectorType>(Accum)->getBitWidth()) {
1177 // Two vectors of the same size: keep Accum.
1179 // Cannot insert an short into a <4 x int> or handle
1180 // <2 x int> -> <4 x int>
1184 // Pointer/FP/Integer unions merge together as integers.
1185 switch (Accum->getTypeID()) {
1186 case Type::PointerTyID: Accum = TD.getIntPtrType(); break;
1187 case Type::FloatTyID: Accum = Type::Int32Ty; break;
1188 case Type::DoubleTyID: Accum = Type::Int64Ty; break;
1189 case Type::X86_FP80TyID: return true;
1190 case Type::FP128TyID: return true;
1191 case Type::PPC_FP128TyID: return true;
1193 assert(Accum->isInteger() && "Unknown FP type!");
1197 switch (In->getTypeID()) {
1198 case Type::PointerTyID: In = TD.getIntPtrType(); break;
1199 case Type::FloatTyID: In = Type::Int32Ty; break;
1200 case Type::DoubleTyID: In = Type::Int64Ty; break;
1201 case Type::X86_FP80TyID: return true;
1202 case Type::FP128TyID: return true;
1203 case Type::PPC_FP128TyID: return true;
1205 assert(In->isInteger() && "Unknown FP type!");
1208 return MergeInType(In, Accum, TD);
1213 /// getIntAtLeastAsBigAs - Return an integer type that is at least as big as the
1214 /// specified type. If there is no suitable type, this returns null.
1215 const Type *getIntAtLeastAsBigAs(unsigned NumBits) {
1216 if (NumBits > 64) return 0;
1217 if (NumBits > 32) return Type::Int64Ty;
1218 if (NumBits > 16) return Type::Int32Ty;
1219 if (NumBits > 8) return Type::Int16Ty;
1220 return Type::Int8Ty;
1223 /// CanConvertToScalar - V is a pointer. If we can convert the pointee to a
1224 /// single scalar integer type, return that type. Further, if the use is not
1225 /// a completely trivial use that mem2reg could promote, set IsNotTrivial. If
1226 /// there are no uses of this pointer, return Type::VoidTy to differentiate from
1229 const Type *SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial) {
1230 const Type *UsedType = Type::VoidTy; // No uses, no forced type.
1231 const PointerType *PTy = cast<PointerType>(V->getType());
1233 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1234 Instruction *User = cast<Instruction>(*UI);
1236 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1237 // FIXME: Loads of a first class aggregrate value could be converted to a
1238 // series of loads and insertvalues
1239 if (!LI->getType()->isSingleValueType())
1242 if (MergeInType(LI->getType(), UsedType, *TD))
1247 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1248 // Storing the pointer, not into the value?
1249 if (SI->getOperand(0) == V) return 0;
1251 // FIXME: Stores of a first class aggregrate value could be converted to a
1252 // series of extractvalues and stores
1253 if (!SI->getOperand(0)->getType()->isSingleValueType())
1256 // NOTE: We could handle storing of FP imms into integers here!
1258 if (MergeInType(SI->getOperand(0)->getType(), UsedType, *TD))
1262 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
1263 IsNotTrivial = true;
1264 const Type *SubTy = CanConvertToScalar(CI, IsNotTrivial);
1265 if (!SubTy || MergeInType(SubTy, UsedType, *TD)) return 0;
1269 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1270 // Check to see if this is stepping over an element: GEP Ptr, int C
1271 if (GEP->getNumOperands() == 2 && isa<ConstantInt>(GEP->getOperand(1))) {
1272 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
1273 unsigned ElSize = TD->getABITypeSize(PTy->getElementType());
1274 unsigned BitOffset = Idx*ElSize*8;
1275 if (BitOffset > 64 || !isPowerOf2_32(ElSize)) return 0;
1277 IsNotTrivial = true;
1278 const Type *SubElt = CanConvertToScalar(GEP, IsNotTrivial);
1279 if (SubElt == 0) return 0;
1280 if (SubElt != Type::VoidTy && SubElt->isInteger()) {
1282 getIntAtLeastAsBigAs(TD->getABITypeSizeInBits(SubElt)+BitOffset);
1283 if (NewTy == 0 || MergeInType(NewTy, UsedType, *TD)) return 0;
1286 // Cannot handle this!
1290 if (GEP->getNumOperands() == 3 &&
1291 isa<ConstantInt>(GEP->getOperand(1)) &&
1292 isa<ConstantInt>(GEP->getOperand(2)) &&
1293 cast<ConstantInt>(GEP->getOperand(1))->isZero()) {
1294 // We are stepping into an element, e.g. a structure or an array:
1295 // GEP Ptr, i32 0, i32 Cst
1296 const Type *AggTy = PTy->getElementType();
1297 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
1299 if (const ArrayType *ATy = dyn_cast<ArrayType>(AggTy)) {
1300 if (Idx >= ATy->getNumElements()) return 0; // Out of range.
1301 } else if (const VectorType *VectorTy = dyn_cast<VectorType>(AggTy)) {
1302 // Getting an element of the vector.
1303 if (Idx >= VectorTy->getNumElements()) return 0; // Out of range.
1305 // Merge in the vector type.
1306 if (MergeInType(VectorTy, UsedType, *TD)) return 0;
1308 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
1309 if (SubTy == 0) return 0;
1311 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, *TD))
1314 // We'll need to change this to an insert/extract element operation.
1315 IsNotTrivial = true;
1316 continue; // Everything looks ok
1318 } else if (isa<StructType>(AggTy)) {
1319 // Structs are always ok.
1323 const Type *NTy = getIntAtLeastAsBigAs(TD->getABITypeSizeInBits(AggTy));
1324 if (NTy == 0 || MergeInType(NTy, UsedType, *TD)) return 0;
1325 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
1326 if (SubTy == 0) return 0;
1327 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, *TD))
1329 continue; // Everything looks ok
1334 // Cannot handle this!
1341 /// ConvertToScalar - The specified alloca passes the CanConvertToScalar
1342 /// predicate and is non-trivial. Convert it to something that can be trivially
1343 /// promoted into a register by mem2reg.
1344 void SROA::ConvertToScalar(AllocationInst *AI, const Type *ActualTy) {
1345 DOUT << "CONVERT TO SCALAR: " << *AI << " TYPE = "
1346 << *ActualTy << "\n";
1349 BasicBlock *EntryBlock = AI->getParent();
1350 assert(EntryBlock == &EntryBlock->getParent()->getEntryBlock() &&
1351 "Not in the entry block!");
1352 EntryBlock->getInstList().remove(AI); // Take the alloca out of the program.
1354 // Create and insert the alloca.
1355 AllocaInst *NewAI = new AllocaInst(ActualTy, 0, AI->getName(),
1356 EntryBlock->begin());
1357 ConvertUsesToScalar(AI, NewAI, 0);
1362 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
1363 /// directly. This happens when we are converting an "integer union" to a
1364 /// single integer scalar, or when we are converting a "vector union" to a
1365 /// vector with insert/extractelement instructions.
1367 /// Offset is an offset from the original alloca, in bits that need to be
1368 /// shifted to the right. By the end of this, there should be no uses of Ptr.
1369 void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset) {
1370 while (!Ptr->use_empty()) {
1371 Instruction *User = cast<Instruction>(Ptr->use_back());
1373 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1374 Value *NV = ConvertUsesOfLoadToScalar(LI, NewAI, Offset);
1375 LI->replaceAllUsesWith(NV);
1376 LI->eraseFromParent();
1380 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1381 assert(SI->getOperand(0) != Ptr && "Consistency error!");
1383 Value *SV = ConvertUsesOfStoreToScalar(SI, NewAI, Offset);
1384 new StoreInst(SV, NewAI, SI);
1385 SI->eraseFromParent();
1389 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
1390 ConvertUsesToScalar(CI, NewAI, Offset);
1391 CI->eraseFromParent();
1395 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1396 const PointerType *AggPtrTy =
1397 cast<PointerType>(GEP->getOperand(0)->getType());
1398 unsigned AggSizeInBits =
1399 TD->getABITypeSizeInBits(AggPtrTy->getElementType());
1401 // Check to see if this is stepping over an element: GEP Ptr, int C
1402 unsigned NewOffset = Offset;
1403 if (GEP->getNumOperands() == 2) {
1404 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
1405 unsigned BitOffset = Idx*AggSizeInBits;
1407 NewOffset += BitOffset;
1408 ConvertUsesToScalar(GEP, NewAI, NewOffset);
1409 GEP->eraseFromParent();
1413 assert(GEP->getNumOperands() == 3 && "Unsupported operation");
1415 // We know that operand #2 is zero.
1416 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
1417 const Type *AggTy = AggPtrTy->getElementType();
1418 if (const SequentialType *SeqTy = dyn_cast<SequentialType>(AggTy)) {
1419 unsigned ElSizeBits =
1420 TD->getABITypeSizeInBits(SeqTy->getElementType());
1422 NewOffset += ElSizeBits*Idx;
1424 const StructType *STy = cast<StructType>(AggTy);
1425 unsigned EltBitOffset =
1426 TD->getStructLayout(STy)->getElementOffsetInBits(Idx);
1428 NewOffset += EltBitOffset;
1430 ConvertUsesToScalar(GEP, NewAI, NewOffset);
1431 GEP->eraseFromParent();
1435 assert(0 && "Unsupported operation!");
1440 /// ConvertUsesOfLoadToScalar - Convert all of the users the specified load to
1441 /// use the new alloca directly, returning the value that should replace the
1442 /// load. This happens when we are converting an "integer union" to a
1443 /// single integer scalar, or when we are converting a "vector union" to a
1444 /// vector with insert/extractelement instructions.
1446 /// Offset is an offset from the original alloca, in bits that need to be
1447 /// shifted to the right. By the end of this, there should be no uses of Ptr.
1448 Value *SROA::ConvertUsesOfLoadToScalar(LoadInst *LI, AllocaInst *NewAI,
1450 // The load is a bit extract from NewAI shifted right by Offset bits.
1451 Value *NV = new LoadInst(NewAI, LI->getName(), LI);
1453 if (NV->getType() == LI->getType() && Offset == 0) {
1454 // We win, no conversion needed.
1458 // If the result type of the 'union' is a pointer, then this must be ptr->ptr
1459 // cast. Anything else would result in NV being an integer.
1460 if (isa<PointerType>(NV->getType())) {
1461 assert(isa<PointerType>(LI->getType()));
1462 return new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1465 if (const VectorType *VTy = dyn_cast<VectorType>(NV->getType())) {
1466 // If the result alloca is a vector type, this is either an element
1467 // access or a bitcast to another vector type.
1468 if (isa<VectorType>(LI->getType()))
1469 return new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1471 // Otherwise it must be an element access.
1474 unsigned EltSize = TD->getABITypeSizeInBits(VTy->getElementType());
1475 Elt = Offset/EltSize;
1476 Offset -= EltSize*Elt;
1478 NV = new ExtractElementInst(NV, ConstantInt::get(Type::Int32Ty, Elt),
1481 // If we're done, return this element.
1482 if (NV->getType() == LI->getType() && Offset == 0)
1486 const IntegerType *NTy = cast<IntegerType>(NV->getType());
1488 // If this is a big-endian system and the load is narrower than the
1489 // full alloca type, we need to do a shift to get the right bits.
1491 if (TD->isBigEndian()) {
1492 // On big-endian machines, the lowest bit is stored at the bit offset
1493 // from the pointer given by getTypeStoreSizeInBits. This matters for
1494 // integers with a bitwidth that is not a multiple of 8.
1495 ShAmt = TD->getTypeStoreSizeInBits(NTy) -
1496 TD->getTypeStoreSizeInBits(LI->getType()) - Offset;
1501 // Note: we support negative bitwidths (with shl) which are not defined.
1502 // We do this to support (f.e.) loads off the end of a structure where
1503 // only some bits are used.
1504 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
1505 NV = BinaryOperator::CreateLShr(NV,
1506 ConstantInt::get(NV->getType(),ShAmt),
1508 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
1509 NV = BinaryOperator::CreateShl(NV,
1510 ConstantInt::get(NV->getType(),-ShAmt),
1513 // Finally, unconditionally truncate the integer to the right width.
1514 unsigned LIBitWidth = TD->getTypeSizeInBits(LI->getType());
1515 if (LIBitWidth < NTy->getBitWidth())
1516 NV = new TruncInst(NV, IntegerType::get(LIBitWidth),
1519 // If the result is an integer, this is a trunc or bitcast.
1520 if (isa<IntegerType>(LI->getType())) {
1522 } else if (LI->getType()->isFloatingPoint()) {
1523 // Just do a bitcast, we know the sizes match up.
1524 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1526 // Otherwise must be a pointer.
1527 NV = new IntToPtrInst(NV, LI->getType(), LI->getName(), LI);
1529 assert(NV->getType() == LI->getType() && "Didn't convert right?");
1534 /// ConvertUsesOfStoreToScalar - Convert the specified store to a load+store
1535 /// pair of the new alloca directly, returning the value that should be stored
1536 /// to the alloca. This happens when we are converting an "integer union" to a
1537 /// single integer scalar, or when we are converting a "vector union" to a
1538 /// vector with insert/extractelement instructions.
1540 /// Offset is an offset from the original alloca, in bits that need to be
1541 /// shifted to the right. By the end of this, there should be no uses of Ptr.
1542 Value *SROA::ConvertUsesOfStoreToScalar(StoreInst *SI, AllocaInst *NewAI,
1545 // Convert the stored type to the actual type, shift it left to insert
1546 // then 'or' into place.
1547 Value *SV = SI->getOperand(0);
1548 const Type *AllocaType = NewAI->getType()->getElementType();
1549 if (SV->getType() == AllocaType && Offset == 0) {
1551 } else if (const VectorType *PTy = dyn_cast<VectorType>(AllocaType)) {
1552 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1554 // If the result alloca is a vector type, this is either an element
1555 // access or a bitcast to another vector type.
1556 if (isa<VectorType>(SV->getType())) {
1557 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1559 // Must be an element insertion.
1560 unsigned Elt = Offset/TD->getABITypeSizeInBits(PTy->getElementType());
1561 SV = InsertElementInst::Create(Old, SV,
1562 ConstantInt::get(Type::Int32Ty, Elt),
1565 } else if (isa<PointerType>(AllocaType)) {
1566 // If the alloca type is a pointer, then all the elements must be
1568 if (SV->getType() != AllocaType)
1569 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1571 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1573 // If SV is a float, convert it to the appropriate integer type.
1574 // If it is a pointer, do the same, and also handle ptr->ptr casts
1576 unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1577 unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1578 unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1579 unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
1580 if (SV->getType()->isFloatingPoint())
1581 SV = new BitCastInst(SV, IntegerType::get(SrcWidth),
1583 else if (isa<PointerType>(SV->getType()))
1584 SV = new PtrToIntInst(SV, TD->getIntPtrType(), SV->getName(), SI);
1586 // Always zero extend the value if needed.
1587 if (SV->getType() != AllocaType)
1588 SV = new ZExtInst(SV, AllocaType, SV->getName(), SI);
1590 // If this is a big-endian system and the store is narrower than the
1591 // full alloca type, we need to do a shift to get the right bits.
1593 if (TD->isBigEndian()) {
1594 // On big-endian machines, the lowest bit is stored at the bit offset
1595 // from the pointer given by getTypeStoreSizeInBits. This matters for
1596 // integers with a bitwidth that is not a multiple of 8.
1597 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
1602 // Note: we support negative bitwidths (with shr) which are not defined.
1603 // We do this to support (f.e.) stores off the end of a structure where
1604 // only some bits in the structure are set.
1605 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1606 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1607 SV = BinaryOperator::CreateShl(SV,
1608 ConstantInt::get(SV->getType(), ShAmt),
1611 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1612 SV = BinaryOperator::CreateLShr(SV,
1613 ConstantInt::get(SV->getType(),-ShAmt),
1615 Mask = Mask.lshr(ShAmt);
1618 // Mask out the bits we are about to insert from the old value, and or
1620 if (SrcWidth != DestWidth) {
1621 assert(DestWidth > SrcWidth);
1622 Old = BinaryOperator::CreateAnd(Old, ConstantInt::get(~Mask),
1623 Old->getName()+".mask", SI);
1624 SV = BinaryOperator::CreateOr(Old, SV, SV->getName()+".ins", SI);
1632 /// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1633 /// some part of a constant global variable. This intentionally only accepts
1634 /// constant expressions because we don't can't rewrite arbitrary instructions.
1635 static bool PointsToConstantGlobal(Value *V) {
1636 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1637 return GV->isConstant();
1638 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1639 if (CE->getOpcode() == Instruction::BitCast ||
1640 CE->getOpcode() == Instruction::GetElementPtr)
1641 return PointsToConstantGlobal(CE->getOperand(0));
1645 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1646 /// pointer to an alloca. Ignore any reads of the pointer, return false if we
1647 /// see any stores or other unknown uses. If we see pointer arithmetic, keep
1648 /// track of whether it moves the pointer (with isOffset) but otherwise traverse
1649 /// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1650 /// the alloca, and if the source pointer is a pointer to a constant global, we
1651 /// can optimize this.
1652 static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1654 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1655 if (isa<LoadInst>(*UI)) {
1656 // Ignore loads, they are always ok.
1659 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1660 // If uses of the bitcast are ok, we are ok.
1661 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1665 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1666 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1667 // doesn't, it does.
1668 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1669 isOffset || !GEP->hasAllZeroIndices()))
1674 // If this is isn't our memcpy/memmove, reject it as something we can't
1676 if (!isa<MemCpyInst>(*UI) && !isa<MemMoveInst>(*UI))
1679 // If we already have seen a copy, reject the second one.
1680 if (TheCopy) return false;
1682 // If the pointer has been offset from the start of the alloca, we can't
1683 // safely handle this.
1684 if (isOffset) return false;
1686 // If the memintrinsic isn't using the alloca as the dest, reject it.
1687 if (UI.getOperandNo() != 1) return false;
1689 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1691 // If the source of the memcpy/move is not a constant global, reject it.
1692 if (!PointsToConstantGlobal(MI->getOperand(2)))
1695 // Otherwise, the transform is safe. Remember the copy instruction.
1701 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1702 /// modified by a copy from a constant global. If we can prove this, we can
1703 /// replace any uses of the alloca with uses of the global directly.
1704 Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocationInst *AI) {
1705 Instruction *TheCopy = 0;
1706 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))