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((intptr_t)&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>();
73 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
74 /// information about the uses. All these fields are initialized to false
75 /// and set to true when something is learned.
77 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
80 /// needsCanon - This is set to true if there is some use of the alloca
81 /// that requires canonicalization.
84 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
87 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
91 : isUnsafe(false), needsCanon(false),
92 isMemCpySrc(false), isMemCpyDst(false) {}
97 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
99 int isSafeAllocaToScalarRepl(AllocationInst *AI);
101 void isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
103 void isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
105 void isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
106 unsigned OpNo, AllocaInfo &Info);
107 void isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI,
110 void DoScalarReplacement(AllocationInst *AI,
111 std::vector<AllocationInst*> &WorkList);
112 void CanonicalizeAllocaUsers(AllocationInst *AI);
113 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
115 void RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
116 SmallVector<AllocaInst*, 32> &NewElts);
118 const Type *CanConvertToScalar(Value *V, bool &IsNotTrivial);
119 void ConvertToScalar(AllocationInst *AI, const Type *Ty);
120 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset);
121 Value *ConvertUsesOfLoadToScalar(LoadInst *LI, AllocaInst *NewAI,
123 Value *ConvertUsesOfStoreToScalar(StoreInst *SI, AllocaInst *NewAI,
125 static Instruction *isOnlyCopiedFromConstantGlobal(AllocationInst *AI);
130 static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
132 // Public interface to the ScalarReplAggregates pass
133 FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
134 return new SROA(Threshold);
138 bool SROA::runOnFunction(Function &F) {
139 bool Changed = performPromotion(F);
141 bool LocalChange = performScalarRepl(F);
142 if (!LocalChange) break; // No need to repromote if no scalarrepl
144 LocalChange = performPromotion(F);
145 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
152 bool SROA::performPromotion(Function &F) {
153 std::vector<AllocaInst*> Allocas;
154 DominatorTree &DT = getAnalysis<DominatorTree>();
155 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
157 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
159 bool Changed = false;
164 // Find allocas that are safe to promote, by looking at all instructions in
166 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
167 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
168 if (isAllocaPromotable(AI))
169 Allocas.push_back(AI);
171 if (Allocas.empty()) break;
173 PromoteMemToReg(Allocas, DT, DF);
174 NumPromoted += Allocas.size();
181 /// getNumSAElements - Return the number of elements in the specific struct or
183 static uint64_t getNumSAElements(const Type *T) {
184 if (const StructType *ST = dyn_cast<StructType>(T))
185 return ST->getNumElements();
186 return cast<ArrayType>(T)->getNumElements();
189 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
190 // which runs on all of the malloc/alloca instructions in the function, removing
191 // them if they are only used by getelementptr instructions.
193 bool SROA::performScalarRepl(Function &F) {
194 std::vector<AllocationInst*> WorkList;
196 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
197 BasicBlock &BB = F.getEntryBlock();
198 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
199 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
200 WorkList.push_back(A);
202 const TargetData &TD = getAnalysis<TargetData>();
204 // Process the worklist
205 bool Changed = false;
206 while (!WorkList.empty()) {
207 AllocationInst *AI = WorkList.back();
210 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
211 // with unused elements.
212 if (AI->use_empty()) {
213 AI->eraseFromParent();
217 // If we can turn this aggregate value (potentially with casts) into a
218 // simple scalar value that can be mem2reg'd into a register value.
219 bool IsNotTrivial = false;
220 if (const Type *ActualType = CanConvertToScalar(AI, IsNotTrivial))
221 if (IsNotTrivial && ActualType != Type::VoidTy) {
222 ConvertToScalar(AI, ActualType);
227 // Check to see if we can perform the core SROA transformation. We cannot
228 // transform the allocation instruction if it is an array allocation
229 // (allocations OF arrays are ok though), and an allocation of a scalar
230 // value cannot be decomposed at all.
231 if (!AI->isArrayAllocation() &&
232 (isa<StructType>(AI->getAllocatedType()) ||
233 isa<ArrayType>(AI->getAllocatedType())) &&
234 AI->getAllocatedType()->isSized() &&
235 // Do not promote any struct whose size is larger than "128" bytes.
236 TD.getABITypeSize(AI->getAllocatedType()) < SRThreshold &&
237 // Do not promote any struct into more than "32" separate vars.
238 getNumSAElements(AI->getAllocatedType()) < SRThreshold/4) {
239 // Check that all of the users of the allocation are capable of being
241 switch (isSafeAllocaToScalarRepl(AI)) {
242 default: assert(0 && "Unexpected value!");
243 case 0: // Not safe to scalar replace.
245 case 1: // Safe, but requires cleanup/canonicalizations first
246 CanonicalizeAllocaUsers(AI);
248 case 3: // Safe to scalar replace.
249 DoScalarReplacement(AI, WorkList);
255 // Check to see if this allocation is only modified by a memcpy/memmove from
256 // a constant global. If this is the case, we can change all users to use
257 // the constant global instead. This is commonly produced by the CFE by
258 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
259 // is only subsequently read.
260 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
261 DOUT << "Found alloca equal to global: " << *AI;
262 DOUT << " memcpy = " << *TheCopy;
263 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
264 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
265 TheCopy->eraseFromParent(); // Don't mutate the global.
266 AI->eraseFromParent();
272 // Otherwise, couldn't process this.
278 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
279 /// predicate, do SROA now.
280 void SROA::DoScalarReplacement(AllocationInst *AI,
281 std::vector<AllocationInst*> &WorkList) {
282 DOUT << "Found inst to SROA: " << *AI;
283 SmallVector<AllocaInst*, 32> ElementAllocas;
284 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
285 ElementAllocas.reserve(ST->getNumContainedTypes());
286 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
287 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
289 AI->getName() + "." + utostr(i), AI);
290 ElementAllocas.push_back(NA);
291 WorkList.push_back(NA); // Add to worklist for recursive processing
294 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
295 ElementAllocas.reserve(AT->getNumElements());
296 const Type *ElTy = AT->getElementType();
297 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
298 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
299 AI->getName() + "." + utostr(i), AI);
300 ElementAllocas.push_back(NA);
301 WorkList.push_back(NA); // Add to worklist for recursive processing
305 // Now that we have created the alloca instructions that we want to use,
306 // expand the getelementptr instructions to use them.
308 while (!AI->use_empty()) {
309 Instruction *User = cast<Instruction>(AI->use_back());
310 if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
311 RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
312 BCInst->eraseFromParent();
317 // %res = load { i32, i32 }* %alloc
319 // %load.0 = load i32* %alloc.0
320 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
321 // %load.1 = load i32* %alloc.1
322 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
323 // (Also works for arrays instead of structs)
324 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
325 Value *Insert = UndefValue::get(LI->getType());
326 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
327 Value *Load = new LoadInst(ElementAllocas[i], "load", LI);
328 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
330 LI->replaceAllUsesWith(Insert);
331 LI->eraseFromParent();
336 // store { i32, i32 } %val, { i32, i32 }* %alloc
338 // %val.0 = extractvalue { i32, i32 } %val, 0
339 // store i32 %val.0, i32* %alloc.0
340 // %val.1 = extractvalue { i32, i32 } %val, 1
341 // store i32 %val.1, i32* %alloc.1
342 // (Also works for arrays instead of structs)
343 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
344 Value *Val = SI->getOperand(0);
345 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
346 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
347 new StoreInst(Extract, ElementAllocas[i], SI);
349 SI->eraseFromParent();
353 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
354 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
356 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
358 assert(Idx < ElementAllocas.size() && "Index out of range?");
359 AllocaInst *AllocaToUse = ElementAllocas[Idx];
362 if (GEPI->getNumOperands() == 3) {
363 // Do not insert a new getelementptr instruction with zero indices, only
364 // to have it optimized out later.
365 RepValue = AllocaToUse;
367 // We are indexing deeply into the structure, so we still need a
368 // getelement ptr instruction to finish the indexing. This may be
369 // expanded itself once the worklist is rerun.
371 SmallVector<Value*, 8> NewArgs;
372 NewArgs.push_back(Constant::getNullValue(Type::Int32Ty));
373 NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
374 RepValue = GetElementPtrInst::Create(AllocaToUse, NewArgs.begin(),
375 NewArgs.end(), "", GEPI);
376 RepValue->takeName(GEPI);
379 // If this GEP is to the start of the aggregate, check for memcpys.
381 bool IsStartOfAggregateGEP = true;
382 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i) {
383 if (!isa<ConstantInt>(GEPI->getOperand(i))) {
384 IsStartOfAggregateGEP = false;
387 if (!cast<ConstantInt>(GEPI->getOperand(i))->isZero()) {
388 IsStartOfAggregateGEP = false;
393 if (IsStartOfAggregateGEP)
394 RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas);
398 // Move all of the users over to the new GEP.
399 GEPI->replaceAllUsesWith(RepValue);
400 // Delete the old GEP
401 GEPI->eraseFromParent();
404 // Finally, delete the Alloca instruction
405 AI->eraseFromParent();
410 /// isSafeElementUse - Check to see if this use is an allowed use for a
411 /// getelementptr instruction of an array aggregate allocation. isFirstElt
412 /// indicates whether Ptr is known to the start of the aggregate.
414 void SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
416 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
418 Instruction *User = cast<Instruction>(*I);
419 switch (User->getOpcode()) {
420 case Instruction::Load: break;
421 case Instruction::Store:
422 // Store is ok if storing INTO the pointer, not storing the pointer
423 if (User->getOperand(0) == Ptr) return MarkUnsafe(Info);
425 case Instruction::GetElementPtr: {
426 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
427 bool AreAllZeroIndices = isFirstElt;
428 if (GEP->getNumOperands() > 1) {
429 if (!isa<ConstantInt>(GEP->getOperand(1)) ||
430 !cast<ConstantInt>(GEP->getOperand(1))->isZero())
431 // Using pointer arithmetic to navigate the array.
432 return MarkUnsafe(Info);
434 if (AreAllZeroIndices) {
435 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) {
436 if (!isa<ConstantInt>(GEP->getOperand(i)) ||
437 !cast<ConstantInt>(GEP->getOperand(i))->isZero()) {
438 AreAllZeroIndices = false;
444 isSafeElementUse(GEP, AreAllZeroIndices, AI, Info);
445 if (Info.isUnsafe) return;
448 case Instruction::BitCast:
450 isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI, Info);
451 if (Info.isUnsafe) return;
454 DOUT << " Transformation preventing inst: " << *User;
455 return MarkUnsafe(Info);
456 case Instruction::Call:
457 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
459 isSafeMemIntrinsicOnAllocation(MI, AI, I.getOperandNo(), Info);
460 if (Info.isUnsafe) return;
464 DOUT << " Transformation preventing inst: " << *User;
465 return MarkUnsafe(Info);
467 DOUT << " Transformation preventing inst: " << *User;
468 return MarkUnsafe(Info);
471 return; // All users look ok :)
474 /// AllUsersAreLoads - Return true if all users of this value are loads.
475 static bool AllUsersAreLoads(Value *Ptr) {
476 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
478 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
483 /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
484 /// aggregate allocation.
486 void SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
488 if (BitCastInst *C = dyn_cast<BitCastInst>(User))
489 return isSafeUseOfBitCastedAllocation(C, AI, Info);
491 if (isa<LoadInst>(User))
492 return; // Loads (returning a first class aggregrate) are always rewritable
494 if (isa<StoreInst>(User) && User->getOperand(0) != AI)
495 return; // Store is ok if storing INTO the pointer, not storing the pointer
497 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User);
499 return MarkUnsafe(Info);
501 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
503 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
505 I.getOperand() != Constant::getNullValue(I.getOperand()->getType())) {
506 return MarkUnsafe(Info);
510 if (I == E) return MarkUnsafe(Info); // ran out of GEP indices??
512 bool IsAllZeroIndices = true;
514 // If this is a use of an array allocation, do a bit more checking for sanity.
515 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
516 uint64_t NumElements = AT->getNumElements();
518 if (ConstantInt *Idx = dyn_cast<ConstantInt>(I.getOperand())) {
519 IsAllZeroIndices &= Idx->isZero();
521 // Check to make sure that index falls within the array. If not,
522 // something funny is going on, so we won't do the optimization.
524 if (Idx->getZExtValue() >= NumElements)
525 return MarkUnsafe(Info);
527 // We cannot scalar repl this level of the array unless any array
528 // sub-indices are in-range constants. In particular, consider:
529 // A[0][i]. We cannot know that the user isn't doing invalid things like
530 // allowing i to index an out-of-range subscript that accesses A[1].
532 // Scalar replacing *just* the outer index of the array is probably not
533 // going to be a win anyway, so just give up.
534 for (++I; I != E && (isa<ArrayType>(*I) || isa<VectorType>(*I)); ++I) {
535 uint64_t NumElements;
536 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*I))
537 NumElements = SubArrayTy->getNumElements();
539 NumElements = cast<VectorType>(*I)->getNumElements();
541 ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
542 if (!IdxVal) return MarkUnsafe(Info);
543 if (IdxVal->getZExtValue() >= NumElements)
544 return MarkUnsafe(Info);
545 IsAllZeroIndices &= IdxVal->isZero();
549 IsAllZeroIndices = 0;
551 // If this is an array index and the index is not constant, we cannot
552 // promote... that is unless the array has exactly one or two elements in
553 // it, in which case we CAN promote it, but we have to canonicalize this
554 // out if this is the only problem.
555 if ((NumElements == 1 || NumElements == 2) &&
556 AllUsersAreLoads(GEPI)) {
557 Info.needsCanon = true;
558 return; // Canonicalization required!
560 return MarkUnsafe(Info);
564 // If there are any non-simple uses of this getelementptr, make sure to reject
566 return isSafeElementUse(GEPI, IsAllZeroIndices, AI, Info);
569 /// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
570 /// intrinsic can be promoted by SROA. At this point, we know that the operand
571 /// of the memintrinsic is a pointer to the beginning of the allocation.
572 void SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
573 unsigned OpNo, AllocaInfo &Info) {
574 // If not constant length, give up.
575 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
576 if (!Length) return MarkUnsafe(Info);
578 // If not the whole aggregate, give up.
579 const TargetData &TD = getAnalysis<TargetData>();
580 if (Length->getZExtValue() !=
581 TD.getABITypeSize(AI->getType()->getElementType()))
582 return MarkUnsafe(Info);
584 // We only know about memcpy/memset/memmove.
585 if (!isa<MemCpyInst>(MI) && !isa<MemSetInst>(MI) && !isa<MemMoveInst>(MI))
586 return MarkUnsafe(Info);
588 // Otherwise, we can transform it. Determine whether this is a memcpy/set
589 // into or out of the aggregate.
591 Info.isMemCpyDst = true;
594 Info.isMemCpySrc = true;
598 /// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
600 void SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI,
602 for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
604 if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
605 isSafeUseOfBitCastedAllocation(BCU, AI, Info);
606 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
607 isSafeMemIntrinsicOnAllocation(MI, AI, UI.getOperandNo(), Info);
609 return MarkUnsafe(Info);
611 if (Info.isUnsafe) return;
615 /// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
616 /// to its first element. Transform users of the cast to use the new values
618 void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
619 SmallVector<AllocaInst*, 32> &NewElts) {
620 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
621 const TargetData &TD = getAnalysis<TargetData>();
623 Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
625 if (BitCastInst *BCU = dyn_cast<BitCastInst>(*UI)) {
626 RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
628 BCU->eraseFromParent();
632 // Otherwise, must be memcpy/memmove/memset of the entire aggregate. Split
633 // into one per element.
634 MemIntrinsic *MI = dyn_cast<MemIntrinsic>(*UI);
636 // If it's not a mem intrinsic, it must be some other user of a gep of the
637 // first pointer. Just leave these alone.
643 // If this is a memcpy/memmove, construct the other pointer as the
646 if (MemCpyInst *MCI = dyn_cast<MemCpyInst>(MI)) {
647 if (BCInst == MCI->getRawDest())
648 OtherPtr = MCI->getRawSource();
650 assert(BCInst == MCI->getRawSource());
651 OtherPtr = MCI->getRawDest();
653 } else if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
654 if (BCInst == MMI->getRawDest())
655 OtherPtr = MMI->getRawSource();
657 assert(BCInst == MMI->getRawSource());
658 OtherPtr = MMI->getRawDest();
662 // If there is an other pointer, we want to convert it to the same pointer
663 // type as AI has, so we can GEP through it.
665 // It is likely that OtherPtr is a bitcast, if so, remove it.
666 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
667 OtherPtr = BC->getOperand(0);
668 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
669 if (BCE->getOpcode() == Instruction::BitCast)
670 OtherPtr = BCE->getOperand(0);
672 // If the pointer is not the right type, insert a bitcast to the right
674 if (OtherPtr->getType() != AI->getType())
675 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
679 // Process each element of the aggregate.
680 Value *TheFn = MI->getOperand(0);
681 const Type *BytePtrTy = MI->getRawDest()->getType();
682 bool SROADest = MI->getRawDest() == BCInst;
684 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
685 // If this is a memcpy/memmove, emit a GEP of the other element address.
688 Value *Idx[2] = { Zero, ConstantInt::get(Type::Int32Ty, i) };
689 OtherElt = GetElementPtrInst::Create(OtherPtr, Idx, Idx + 2,
690 OtherPtr->getNameStr()+"."+utostr(i),
694 Value *EltPtr = NewElts[i];
695 const Type *EltTy =cast<PointerType>(EltPtr->getType())->getElementType();
697 // If we got down to a scalar, insert a load or store as appropriate.
698 if (EltTy->isSingleValueType()) {
699 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
700 Value *Elt = new LoadInst(SROADest ? OtherElt : EltPtr, "tmp",
702 new StoreInst(Elt, SROADest ? EltPtr : OtherElt, MI);
705 assert(isa<MemSetInst>(MI));
707 // If the stored element is zero (common case), just store a null
710 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
712 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
714 // If EltTy is a vector type, get the element type.
715 const Type *ValTy = EltTy;
716 if (const VectorType *VTy = dyn_cast<VectorType>(ValTy))
717 ValTy = VTy->getElementType();
719 // Construct an integer with the right value.
720 unsigned EltSize = TD.getTypeSizeInBits(ValTy);
721 APInt OneVal(EltSize, CI->getZExtValue());
722 APInt TotalVal(OneVal);
724 for (unsigned i = 0; 8*i < EltSize; ++i) {
725 TotalVal = TotalVal.shl(8);
729 // Convert the integer value to the appropriate type.
730 StoreVal = ConstantInt::get(TotalVal);
731 if (isa<PointerType>(ValTy))
732 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
733 else if (ValTy->isFloatingPoint())
734 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
735 assert(StoreVal->getType() == ValTy && "Type mismatch!");
737 // If the requested value was a vector constant, create it.
738 if (EltTy != ValTy) {
739 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
740 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
741 StoreVal = ConstantVector::get(&Elts[0], NumElts);
744 new StoreInst(StoreVal, EltPtr, MI);
747 // Otherwise, if we're storing a byte variable, use a memset call for
752 // Cast the element pointer to BytePtrTy.
753 if (EltPtr->getType() != BytePtrTy)
754 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
756 // Cast the other pointer (if we have one) to BytePtrTy.
757 if (OtherElt && OtherElt->getType() != BytePtrTy)
758 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
761 unsigned EltSize = TD.getABITypeSize(EltTy);
763 // Finally, insert the meminst for this element.
764 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
766 SROADest ? EltPtr : OtherElt, // Dest ptr
767 SROADest ? OtherElt : EltPtr, // Src ptr
768 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
771 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
773 assert(isa<MemSetInst>(MI));
775 EltPtr, MI->getOperand(2), // Dest, Value,
776 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
779 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
783 // Finally, MI is now dead, as we've modified its actions to occur on all of
784 // the elements of the aggregate.
786 MI->eraseFromParent();
790 /// HasPadding - Return true if the specified type has any structure or
791 /// alignment padding, false otherwise.
792 static bool HasPadding(const Type *Ty, const TargetData &TD) {
793 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
794 const StructLayout *SL = TD.getStructLayout(STy);
795 unsigned PrevFieldBitOffset = 0;
796 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
797 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
799 // Padding in sub-elements?
800 if (HasPadding(STy->getElementType(i), TD))
803 // Check to see if there is any padding between this element and the
806 unsigned PrevFieldEnd =
807 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
808 if (PrevFieldEnd < FieldBitOffset)
812 PrevFieldBitOffset = FieldBitOffset;
815 // Check for tail padding.
816 if (unsigned EltCount = STy->getNumElements()) {
817 unsigned PrevFieldEnd = PrevFieldBitOffset +
818 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
819 if (PrevFieldEnd < SL->getSizeInBits())
823 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
824 return HasPadding(ATy->getElementType(), TD);
825 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
826 return HasPadding(VTy->getElementType(), TD);
828 return TD.getTypeSizeInBits(Ty) != TD.getABITypeSizeInBits(Ty);
831 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
832 /// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
833 /// or 1 if safe after canonicalization has been performed.
835 int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
836 // Loop over the use list of the alloca. We can only transform it if all of
837 // the users are safe to transform.
840 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
842 isSafeUseOfAllocation(cast<Instruction>(*I), AI, Info);
844 DOUT << "Cannot transform: " << *AI << " due to user: " << **I;
849 // Okay, we know all the users are promotable. If the aggregate is a memcpy
850 // source and destination, we have to be careful. In particular, the memcpy
851 // could be moving around elements that live in structure padding of the LLVM
852 // types, but may actually be used. In these cases, we refuse to promote the
854 if (Info.isMemCpySrc && Info.isMemCpyDst &&
855 HasPadding(AI->getType()->getElementType(), getAnalysis<TargetData>()))
858 // If we require cleanup, return 1, otherwise return 3.
859 return Info.needsCanon ? 1 : 3;
862 /// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified
863 /// allocation, but only if cleaned up, perform the cleanups required.
864 void SROA::CanonicalizeAllocaUsers(AllocationInst *AI) {
865 // At this point, we know that the end result will be SROA'd and promoted, so
866 // we can insert ugly code if required so long as sroa+mem2reg will clean it
868 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
870 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI++);
872 gep_type_iterator I = gep_type_begin(GEPI);
875 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
876 uint64_t NumElements = AT->getNumElements();
878 if (!isa<ConstantInt>(I.getOperand())) {
879 if (NumElements == 1) {
880 GEPI->setOperand(2, Constant::getNullValue(Type::Int32Ty));
882 assert(NumElements == 2 && "Unhandled case!");
883 // All users of the GEP must be loads. At each use of the GEP, insert
884 // two loads of the appropriate indexed GEP and select between them.
885 Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(),
886 Constant::getNullValue(I.getOperand()->getType()),
888 // Insert the new GEP instructions, which are properly indexed.
889 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
890 Indices[1] = Constant::getNullValue(Type::Int32Ty);
891 Value *ZeroIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
894 GEPI->getName()+".0", GEPI);
895 Indices[1] = ConstantInt::get(Type::Int32Ty, 1);
896 Value *OneIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
899 GEPI->getName()+".1", GEPI);
900 // Replace all loads of the variable index GEP with loads from both
901 // indexes and a select.
902 while (!GEPI->use_empty()) {
903 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
904 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
905 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
906 Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI);
907 LI->replaceAllUsesWith(R);
908 LI->eraseFromParent();
910 GEPI->eraseFromParent();
917 /// MergeInType - Add the 'In' type to the accumulated type so far. If the
918 /// types are incompatible, return true, otherwise update Accum and return
921 /// There are three cases we handle here:
922 /// 1) An effectively-integer union, where the pieces are stored into as
923 /// smaller integers (common with byte swap and other idioms).
924 /// 2) A union of vector types of the same size and potentially its elements.
925 /// Here we turn element accesses into insert/extract element operations.
926 /// 3) A union of scalar types, such as int/float or int/pointer. Here we
927 /// merge together into integers, allowing the xform to work with #1 as
929 static bool MergeInType(const Type *In, const Type *&Accum,
930 const TargetData &TD) {
931 // If this is our first type, just use it.
932 const VectorType *PTy;
933 if (Accum == Type::VoidTy || In == Accum) {
935 } else if (In == Type::VoidTy) {
937 } else if (In->isInteger() && Accum->isInteger()) { // integer union.
938 // Otherwise pick whichever type is larger.
939 if (cast<IntegerType>(In)->getBitWidth() >
940 cast<IntegerType>(Accum)->getBitWidth())
942 } else if (isa<PointerType>(In) && isa<PointerType>(Accum)) {
943 // Pointer unions just stay as one of the pointers.
944 } else if (isa<VectorType>(In) || isa<VectorType>(Accum)) {
945 if ((PTy = dyn_cast<VectorType>(Accum)) &&
946 PTy->getElementType() == In) {
947 // Accum is a vector, and we are accessing an element: ok.
948 } else if ((PTy = dyn_cast<VectorType>(In)) &&
949 PTy->getElementType() == Accum) {
950 // In is a vector, and accum is an element: ok, remember In.
952 } else if ((PTy = dyn_cast<VectorType>(In)) && isa<VectorType>(Accum) &&
953 PTy->getBitWidth() == cast<VectorType>(Accum)->getBitWidth()) {
954 // Two vectors of the same size: keep Accum.
956 // Cannot insert an short into a <4 x int> or handle
957 // <2 x int> -> <4 x int>
961 // Pointer/FP/Integer unions merge together as integers.
962 switch (Accum->getTypeID()) {
963 case Type::PointerTyID: Accum = TD.getIntPtrType(); break;
964 case Type::FloatTyID: Accum = Type::Int32Ty; break;
965 case Type::DoubleTyID: Accum = Type::Int64Ty; break;
966 case Type::X86_FP80TyID: return true;
967 case Type::FP128TyID: return true;
968 case Type::PPC_FP128TyID: return true;
970 assert(Accum->isInteger() && "Unknown FP type!");
974 switch (In->getTypeID()) {
975 case Type::PointerTyID: In = TD.getIntPtrType(); break;
976 case Type::FloatTyID: In = Type::Int32Ty; break;
977 case Type::DoubleTyID: In = Type::Int64Ty; break;
978 case Type::X86_FP80TyID: return true;
979 case Type::FP128TyID: return true;
980 case Type::PPC_FP128TyID: return true;
982 assert(In->isInteger() && "Unknown FP type!");
985 return MergeInType(In, Accum, TD);
990 /// getUIntAtLeastAsBigAs - Return an unsigned integer type that is at least
991 /// as big as the specified type. If there is no suitable type, this returns
993 const Type *getUIntAtLeastAsBigAs(unsigned NumBits) {
994 if (NumBits > 64) return 0;
995 if (NumBits > 32) return Type::Int64Ty;
996 if (NumBits > 16) return Type::Int32Ty;
997 if (NumBits > 8) return Type::Int16Ty;
1001 /// CanConvertToScalar - V is a pointer. If we can convert the pointee to a
1002 /// single scalar integer type, return that type. Further, if the use is not
1003 /// a completely trivial use that mem2reg could promote, set IsNotTrivial. If
1004 /// there are no uses of this pointer, return Type::VoidTy to differentiate from
1007 const Type *SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial) {
1008 const Type *UsedType = Type::VoidTy; // No uses, no forced type.
1009 const TargetData &TD = getAnalysis<TargetData>();
1010 const PointerType *PTy = cast<PointerType>(V->getType());
1012 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1013 Instruction *User = cast<Instruction>(*UI);
1015 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1016 // FIXME: Loads of a first class aggregrate value could be converted to a
1017 // series of loads and insertvalues
1018 if (!LI->getType()->isSingleValueType())
1021 if (MergeInType(LI->getType(), UsedType, TD))
1024 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1025 // Storing the pointer, not into the value?
1026 if (SI->getOperand(0) == V) return 0;
1028 // FIXME: Stores of a first class aggregrate value could be converted to a
1029 // series of extractvalues and stores
1030 if (!SI->getOperand(0)->getType()->isSingleValueType())
1033 // NOTE: We could handle storing of FP imms into integers here!
1035 if (MergeInType(SI->getOperand(0)->getType(), UsedType, TD))
1037 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
1038 IsNotTrivial = true;
1039 const Type *SubTy = CanConvertToScalar(CI, IsNotTrivial);
1040 if (!SubTy || MergeInType(SubTy, UsedType, TD)) return 0;
1041 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1042 // Check to see if this is stepping over an element: GEP Ptr, int C
1043 if (GEP->getNumOperands() == 2 && isa<ConstantInt>(GEP->getOperand(1))) {
1044 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
1045 unsigned ElSize = TD.getABITypeSize(PTy->getElementType());
1046 unsigned BitOffset = Idx*ElSize*8;
1047 if (BitOffset > 64 || !isPowerOf2_32(ElSize)) return 0;
1049 IsNotTrivial = true;
1050 const Type *SubElt = CanConvertToScalar(GEP, IsNotTrivial);
1051 if (SubElt == 0) return 0;
1052 if (SubElt != Type::VoidTy && SubElt->isInteger()) {
1054 getUIntAtLeastAsBigAs(TD.getABITypeSizeInBits(SubElt)+BitOffset);
1055 if (NewTy == 0 || MergeInType(NewTy, UsedType, TD)) return 0;
1058 } else if (GEP->getNumOperands() == 3 &&
1059 isa<ConstantInt>(GEP->getOperand(1)) &&
1060 isa<ConstantInt>(GEP->getOperand(2)) &&
1061 cast<ConstantInt>(GEP->getOperand(1))->isZero()) {
1062 // We are stepping into an element, e.g. a structure or an array:
1063 // GEP Ptr, int 0, uint C
1064 const Type *AggTy = PTy->getElementType();
1065 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
1067 if (const ArrayType *ATy = dyn_cast<ArrayType>(AggTy)) {
1068 if (Idx >= ATy->getNumElements()) return 0; // Out of range.
1069 } else if (const VectorType *VectorTy = dyn_cast<VectorType>(AggTy)) {
1070 // Getting an element of the vector.
1071 if (Idx >= VectorTy->getNumElements()) return 0; // Out of range.
1073 // Merge in the vector type.
1074 if (MergeInType(VectorTy, UsedType, TD)) return 0;
1076 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
1077 if (SubTy == 0) return 0;
1079 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
1082 // We'll need to change this to an insert/extract element operation.
1083 IsNotTrivial = true;
1084 continue; // Everything looks ok
1086 } else if (isa<StructType>(AggTy)) {
1087 // Structs are always ok.
1091 const Type *NTy = getUIntAtLeastAsBigAs(TD.getABITypeSizeInBits(AggTy));
1092 if (NTy == 0 || MergeInType(NTy, UsedType, TD)) return 0;
1093 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
1094 if (SubTy == 0) return 0;
1095 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
1097 continue; // Everything looks ok
1101 // Cannot handle this!
1109 /// ConvertToScalar - The specified alloca passes the CanConvertToScalar
1110 /// predicate and is non-trivial. Convert it to something that can be trivially
1111 /// promoted into a register by mem2reg.
1112 void SROA::ConvertToScalar(AllocationInst *AI, const Type *ActualTy) {
1113 DOUT << "CONVERT TO SCALAR: " << *AI << " TYPE = "
1114 << *ActualTy << "\n";
1117 BasicBlock *EntryBlock = AI->getParent();
1118 assert(EntryBlock == &EntryBlock->getParent()->getEntryBlock() &&
1119 "Not in the entry block!");
1120 EntryBlock->getInstList().remove(AI); // Take the alloca out of the program.
1122 // Create and insert the alloca.
1123 AllocaInst *NewAI = new AllocaInst(ActualTy, 0, AI->getName(),
1124 EntryBlock->begin());
1125 ConvertUsesToScalar(AI, NewAI, 0);
1130 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
1131 /// directly. This happens when we are converting an "integer union" to a
1132 /// single integer scalar, or when we are converting a "vector union" to a
1133 /// vector with insert/extractelement instructions.
1135 /// Offset is an offset from the original alloca, in bits that need to be
1136 /// shifted to the right. By the end of this, there should be no uses of Ptr.
1137 void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset) {
1138 while (!Ptr->use_empty()) {
1139 Instruction *User = cast<Instruction>(Ptr->use_back());
1141 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1142 Value *NV = ConvertUsesOfLoadToScalar(LI, NewAI, Offset);
1143 LI->replaceAllUsesWith(NV);
1144 LI->eraseFromParent();
1145 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1146 assert(SI->getOperand(0) != Ptr && "Consistency error!");
1148 Value *SV = ConvertUsesOfStoreToScalar(SI, NewAI, Offset);
1149 new StoreInst(SV, NewAI, SI);
1150 SI->eraseFromParent();
1152 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
1153 ConvertUsesToScalar(CI, NewAI, Offset);
1154 CI->eraseFromParent();
1155 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1156 const PointerType *AggPtrTy =
1157 cast<PointerType>(GEP->getOperand(0)->getType());
1158 const TargetData &TD = getAnalysis<TargetData>();
1159 unsigned AggSizeInBits =
1160 TD.getABITypeSizeInBits(AggPtrTy->getElementType());
1162 // Check to see if this is stepping over an element: GEP Ptr, int C
1163 unsigned NewOffset = Offset;
1164 if (GEP->getNumOperands() == 2) {
1165 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
1166 unsigned BitOffset = Idx*AggSizeInBits;
1168 NewOffset += BitOffset;
1169 } else if (GEP->getNumOperands() == 3) {
1170 // We know that operand #2 is zero.
1171 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
1172 const Type *AggTy = AggPtrTy->getElementType();
1173 if (const SequentialType *SeqTy = dyn_cast<SequentialType>(AggTy)) {
1174 unsigned ElSizeBits =
1175 TD.getABITypeSizeInBits(SeqTy->getElementType());
1177 NewOffset += ElSizeBits*Idx;
1178 } else if (const StructType *STy = dyn_cast<StructType>(AggTy)) {
1179 unsigned EltBitOffset =
1180 TD.getStructLayout(STy)->getElementOffsetInBits(Idx);
1182 NewOffset += EltBitOffset;
1184 assert(0 && "Unsupported operation!");
1188 assert(0 && "Unsupported operation!");
1191 ConvertUsesToScalar(GEP, NewAI, NewOffset);
1192 GEP->eraseFromParent();
1194 assert(0 && "Unsupported operation!");
1200 /// ConvertUsesOfLoadToScalar - Convert all of the users the specified load to
1201 /// use the new alloca directly, returning the value that should replace the
1202 /// load. This happens when we are converting an "integer union" to a
1203 /// single integer scalar, or when we are converting a "vector union" to a
1204 /// vector with insert/extractelement instructions.
1206 /// Offset is an offset from the original alloca, in bits that need to be
1207 /// shifted to the right. By the end of this, there should be no uses of Ptr.
1208 Value *SROA::ConvertUsesOfLoadToScalar(LoadInst *LI, AllocaInst *NewAI,
1210 // The load is a bit extract from NewAI shifted right by Offset bits.
1211 Value *NV = new LoadInst(NewAI, LI->getName(), LI);
1213 if (NV->getType() == LI->getType() && Offset == 0) {
1214 // We win, no conversion needed.
1218 // If the result type of the 'union' is a pointer, then this must be ptr->ptr
1219 // cast. Anything else would result in NV being an integer.
1220 if (isa<PointerType>(NV->getType())) {
1221 assert(isa<PointerType>(LI->getType()));
1222 return new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1225 if (const VectorType *VTy = dyn_cast<VectorType>(NV->getType())) {
1226 // If the result alloca is a vector type, this is either an element
1227 // access or a bitcast to another vector type.
1228 if (isa<VectorType>(LI->getType()))
1229 return new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1231 // Otherwise it must be an element access.
1232 const TargetData &TD = getAnalysis<TargetData>();
1235 unsigned EltSize = TD.getABITypeSizeInBits(VTy->getElementType());
1236 Elt = Offset/EltSize;
1237 Offset -= EltSize*Elt;
1239 NV = new ExtractElementInst(NV, ConstantInt::get(Type::Int32Ty, Elt),
1242 // If we're done, return this element.
1243 if (NV->getType() == LI->getType() && Offset == 0)
1247 const IntegerType *NTy = cast<IntegerType>(NV->getType());
1249 // If this is a big-endian system and the load is narrower than the
1250 // full alloca type, we need to do a shift to get the right bits.
1252 const TargetData &TD = getAnalysis<TargetData>();
1253 if (TD.isBigEndian()) {
1254 // On big-endian machines, the lowest bit is stored at the bit offset
1255 // from the pointer given by getTypeStoreSizeInBits. This matters for
1256 // integers with a bitwidth that is not a multiple of 8.
1257 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
1258 TD.getTypeStoreSizeInBits(LI->getType()) - Offset;
1263 // Note: we support negative bitwidths (with shl) which are not defined.
1264 // We do this to support (f.e.) loads off the end of a structure where
1265 // only some bits are used.
1266 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
1267 NV = BinaryOperator::CreateLShr(NV,
1268 ConstantInt::get(NV->getType(),ShAmt),
1270 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
1271 NV = BinaryOperator::CreateShl(NV,
1272 ConstantInt::get(NV->getType(),-ShAmt),
1275 // Finally, unconditionally truncate the integer to the right width.
1276 unsigned LIBitWidth = TD.getTypeSizeInBits(LI->getType());
1277 if (LIBitWidth < NTy->getBitWidth())
1278 NV = new TruncInst(NV, IntegerType::get(LIBitWidth),
1281 // If the result is an integer, this is a trunc or bitcast.
1282 if (isa<IntegerType>(LI->getType())) {
1284 } else if (LI->getType()->isFloatingPoint()) {
1285 // Just do a bitcast, we know the sizes match up.
1286 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1288 // Otherwise must be a pointer.
1289 NV = new IntToPtrInst(NV, LI->getType(), LI->getName(), LI);
1291 assert(NV->getType() == LI->getType() && "Didn't convert right?");
1296 /// ConvertUsesOfStoreToScalar - Convert the specified store to a load+store
1297 /// pair of the new alloca directly, returning the value that should be stored
1298 /// to the alloca. This happens when we are converting an "integer union" to a
1299 /// single integer scalar, or when we are converting a "vector union" to a
1300 /// vector with insert/extractelement instructions.
1302 /// Offset is an offset from the original alloca, in bits that need to be
1303 /// shifted to the right. By the end of this, there should be no uses of Ptr.
1304 Value *SROA::ConvertUsesOfStoreToScalar(StoreInst *SI, AllocaInst *NewAI,
1307 // Convert the stored type to the actual type, shift it left to insert
1308 // then 'or' into place.
1309 Value *SV = SI->getOperand(0);
1310 const Type *AllocaType = NewAI->getType()->getElementType();
1311 if (SV->getType() == AllocaType && Offset == 0) {
1313 } else if (const VectorType *PTy = dyn_cast<VectorType>(AllocaType)) {
1314 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1316 // If the result alloca is a vector type, this is either an element
1317 // access or a bitcast to another vector type.
1318 if (isa<VectorType>(SV->getType())) {
1319 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1321 // Must be an element insertion.
1322 const TargetData &TD = getAnalysis<TargetData>();
1323 unsigned Elt = Offset/TD.getABITypeSizeInBits(PTy->getElementType());
1324 SV = InsertElementInst::Create(Old, SV,
1325 ConstantInt::get(Type::Int32Ty, Elt),
1328 } else if (isa<PointerType>(AllocaType)) {
1329 // If the alloca type is a pointer, then all the elements must be
1331 if (SV->getType() != AllocaType)
1332 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1334 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1336 // If SV is a float, convert it to the appropriate integer type.
1337 // If it is a pointer, do the same, and also handle ptr->ptr casts
1339 const TargetData &TD = getAnalysis<TargetData>();
1340 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
1341 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
1342 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
1343 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
1344 if (SV->getType()->isFloatingPoint())
1345 SV = new BitCastInst(SV, IntegerType::get(SrcWidth),
1347 else if (isa<PointerType>(SV->getType()))
1348 SV = new PtrToIntInst(SV, TD.getIntPtrType(), SV->getName(), SI);
1350 // Always zero extend the value if needed.
1351 if (SV->getType() != AllocaType)
1352 SV = new ZExtInst(SV, AllocaType, SV->getName(), SI);
1354 // If this is a big-endian system and the store is narrower than the
1355 // full alloca type, we need to do a shift to get the right bits.
1357 if (TD.isBigEndian()) {
1358 // On big-endian machines, the lowest bit is stored at the bit offset
1359 // from the pointer given by getTypeStoreSizeInBits. This matters for
1360 // integers with a bitwidth that is not a multiple of 8.
1361 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
1366 // Note: we support negative bitwidths (with shr) which are not defined.
1367 // We do this to support (f.e.) stores off the end of a structure where
1368 // only some bits in the structure are set.
1369 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1370 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1371 SV = BinaryOperator::CreateShl(SV,
1372 ConstantInt::get(SV->getType(), ShAmt),
1375 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1376 SV = BinaryOperator::CreateLShr(SV,
1377 ConstantInt::get(SV->getType(),-ShAmt),
1379 Mask = Mask.lshr(ShAmt);
1382 // Mask out the bits we are about to insert from the old value, and or
1384 if (SrcWidth != DestWidth) {
1385 assert(DestWidth > SrcWidth);
1386 Old = BinaryOperator::CreateAnd(Old, ConstantInt::get(~Mask),
1387 Old->getName()+".mask", SI);
1388 SV = BinaryOperator::CreateOr(Old, SV, SV->getName()+".ins", SI);
1396 /// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1397 /// some part of a constant global variable. This intentionally only accepts
1398 /// constant expressions because we don't can't rewrite arbitrary instructions.
1399 static bool PointsToConstantGlobal(Value *V) {
1400 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1401 return GV->isConstant();
1402 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1403 if (CE->getOpcode() == Instruction::BitCast ||
1404 CE->getOpcode() == Instruction::GetElementPtr)
1405 return PointsToConstantGlobal(CE->getOperand(0));
1409 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1410 /// pointer to an alloca. Ignore any reads of the pointer, return false if we
1411 /// see any stores or other unknown uses. If we see pointer arithmetic, keep
1412 /// track of whether it moves the pointer (with isOffset) but otherwise traverse
1413 /// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1414 /// the alloca, and if the source pointer is a pointer to a constant global, we
1415 /// can optimize this.
1416 static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1418 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1419 if (isa<LoadInst>(*UI)) {
1420 // Ignore loads, they are always ok.
1423 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1424 // If uses of the bitcast are ok, we are ok.
1425 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1429 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1430 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1431 // doesn't, it does.
1432 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1433 isOffset || !GEP->hasAllZeroIndices()))
1438 // If this is isn't our memcpy/memmove, reject it as something we can't
1440 if (!isa<MemCpyInst>(*UI) && !isa<MemMoveInst>(*UI))
1443 // If we already have seen a copy, reject the second one.
1444 if (TheCopy) return false;
1446 // If the pointer has been offset from the start of the alloca, we can't
1447 // safely handle this.
1448 if (isOffset) return false;
1450 // If the memintrinsic isn't using the alloca as the dest, reject it.
1451 if (UI.getOperandNo() != 1) return false;
1453 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1455 // If the source of the memcpy/move is not a constant global, reject it.
1456 if (!PointsToConstantGlobal(MI->getOperand(2)))
1459 // Otherwise, the transform is safe. Remember the copy instruction.
1465 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1466 /// modified by a copy from a constant global. If we can prove this, we can
1467 /// replace any uses of the alloca with uses of the global directly.
1468 Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocationInst *AI) {
1469 Instruction *TheCopy = 0;
1470 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))