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 const Type *CanConvertToScalar(Value *V, bool &IsNotTrivial);
121 void ConvertToScalar(AllocationInst *AI, const Type *Ty);
122 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset);
123 Value *ConvertUsesOfLoadToScalar(LoadInst *LI, AllocaInst *NewAI,
125 Value *ConvertUsesOfStoreToScalar(StoreInst *SI, AllocaInst *NewAI,
127 static Instruction *isOnlyCopiedFromConstantGlobal(AllocationInst *AI);
132 static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
134 // Public interface to the ScalarReplAggregates pass
135 FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
136 return new SROA(Threshold);
140 bool SROA::runOnFunction(Function &F) {
141 TD = &getAnalysis<TargetData>();
143 bool Changed = performPromotion(F);
145 bool LocalChange = performScalarRepl(F);
146 if (!LocalChange) break; // No need to repromote if no scalarrepl
148 LocalChange = performPromotion(F);
149 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
156 bool SROA::performPromotion(Function &F) {
157 std::vector<AllocaInst*> Allocas;
158 DominatorTree &DT = getAnalysis<DominatorTree>();
159 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
161 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
163 bool Changed = false;
168 // Find allocas that are safe to promote, by looking at all instructions in
170 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
171 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
172 if (isAllocaPromotable(AI))
173 Allocas.push_back(AI);
175 if (Allocas.empty()) break;
177 PromoteMemToReg(Allocas, DT, DF);
178 NumPromoted += Allocas.size();
185 /// getNumSAElements - Return the number of elements in the specific struct or
187 static uint64_t getNumSAElements(const Type *T) {
188 if (const StructType *ST = dyn_cast<StructType>(T))
189 return ST->getNumElements();
190 return cast<ArrayType>(T)->getNumElements();
193 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
194 // which runs on all of the malloc/alloca instructions in the function, removing
195 // them if they are only used by getelementptr instructions.
197 bool SROA::performScalarRepl(Function &F) {
198 std::vector<AllocationInst*> WorkList;
200 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
201 BasicBlock &BB = F.getEntryBlock();
202 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
203 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
204 WorkList.push_back(A);
206 // Process the worklist
207 bool Changed = false;
208 while (!WorkList.empty()) {
209 AllocationInst *AI = WorkList.back();
212 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
213 // with unused elements.
214 if (AI->use_empty()) {
215 AI->eraseFromParent();
219 // If we can turn this aggregate value (potentially with casts) into a
220 // simple scalar value that can be mem2reg'd into a register value.
221 bool IsNotTrivial = false;
222 if (const Type *ActualType = CanConvertToScalar(AI, IsNotTrivial))
223 if (IsNotTrivial && ActualType != Type::VoidTy) {
224 ConvertToScalar(AI, ActualType);
229 // Check to see if we can perform the core SROA transformation. We cannot
230 // transform the allocation instruction if it is an array allocation
231 // (allocations OF arrays are ok though), and an allocation of a scalar
232 // value cannot be decomposed at all.
233 if (!AI->isArrayAllocation() &&
234 (isa<StructType>(AI->getAllocatedType()) ||
235 isa<ArrayType>(AI->getAllocatedType())) &&
236 AI->getAllocatedType()->isSized() &&
237 // Do not promote any struct whose size is larger than "128" bytes.
238 TD->getABITypeSize(AI->getAllocatedType()) < SRThreshold &&
239 // Do not promote any struct into more than "32" separate vars.
240 getNumSAElements(AI->getAllocatedType()) < SRThreshold/4) {
241 // Check that all of the users of the allocation are capable of being
243 switch (isSafeAllocaToScalarRepl(AI)) {
244 default: assert(0 && "Unexpected value!");
245 case 0: // Not safe to scalar replace.
247 case 1: // Safe, but requires cleanup/canonicalizations first
248 CanonicalizeAllocaUsers(AI);
250 case 3: // Safe to scalar replace.
251 DoScalarReplacement(AI, WorkList);
257 // Check to see if this allocation is only modified by a memcpy/memmove from
258 // a constant global. If this is the case, we can change all users to use
259 // the constant global instead. This is commonly produced by the CFE by
260 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
261 // is only subsequently read.
262 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
263 DOUT << "Found alloca equal to global: " << *AI;
264 DOUT << " memcpy = " << *TheCopy;
265 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
266 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
267 TheCopy->eraseFromParent(); // Don't mutate the global.
268 AI->eraseFromParent();
274 // Otherwise, couldn't process this.
280 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
281 /// predicate, do SROA now.
282 void SROA::DoScalarReplacement(AllocationInst *AI,
283 std::vector<AllocationInst*> &WorkList) {
284 DOUT << "Found inst to SROA: " << *AI;
285 SmallVector<AllocaInst*, 32> ElementAllocas;
286 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
287 ElementAllocas.reserve(ST->getNumContainedTypes());
288 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
289 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
291 AI->getName() + "." + utostr(i), AI);
292 ElementAllocas.push_back(NA);
293 WorkList.push_back(NA); // Add to worklist for recursive processing
296 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
297 ElementAllocas.reserve(AT->getNumElements());
298 const Type *ElTy = AT->getElementType();
299 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
300 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
301 AI->getName() + "." + utostr(i), AI);
302 ElementAllocas.push_back(NA);
303 WorkList.push_back(NA); // Add to worklist for recursive processing
307 // Now that we have created the alloca instructions that we want to use,
308 // expand the getelementptr instructions to use them.
310 while (!AI->use_empty()) {
311 Instruction *User = cast<Instruction>(AI->use_back());
312 if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
313 RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
314 BCInst->eraseFromParent();
319 // %res = load { i32, i32 }* %alloc
321 // %load.0 = load i32* %alloc.0
322 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
323 // %load.1 = load i32* %alloc.1
324 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
325 // (Also works for arrays instead of structs)
326 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
327 Value *Insert = UndefValue::get(LI->getType());
328 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
329 Value *Load = new LoadInst(ElementAllocas[i], "load", LI);
330 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
332 LI->replaceAllUsesWith(Insert);
333 LI->eraseFromParent();
338 // store { i32, i32 } %val, { i32, i32 }* %alloc
340 // %val.0 = extractvalue { i32, i32 } %val, 0
341 // store i32 %val.0, i32* %alloc.0
342 // %val.1 = extractvalue { i32, i32 } %val, 1
343 // store i32 %val.1, i32* %alloc.1
344 // (Also works for arrays instead of structs)
345 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
346 Value *Val = SI->getOperand(0);
347 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
348 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
349 new StoreInst(Extract, ElementAllocas[i], SI);
351 SI->eraseFromParent();
355 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
356 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
358 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
360 assert(Idx < ElementAllocas.size() && "Index out of range?");
361 AllocaInst *AllocaToUse = ElementAllocas[Idx];
364 if (GEPI->getNumOperands() == 3) {
365 // Do not insert a new getelementptr instruction with zero indices, only
366 // to have it optimized out later.
367 RepValue = AllocaToUse;
369 // We are indexing deeply into the structure, so we still need a
370 // getelement ptr instruction to finish the indexing. This may be
371 // expanded itself once the worklist is rerun.
373 SmallVector<Value*, 8> NewArgs;
374 NewArgs.push_back(Constant::getNullValue(Type::Int32Ty));
375 NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
376 RepValue = GetElementPtrInst::Create(AllocaToUse, NewArgs.begin(),
377 NewArgs.end(), "", GEPI);
378 RepValue->takeName(GEPI);
381 // If this GEP is to the start of the aggregate, check for memcpys.
382 if (Idx == 0 && GEPI->hasAllZeroIndices())
383 RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas);
385 // Move all of the users over to the new GEP.
386 GEPI->replaceAllUsesWith(RepValue);
387 // Delete the old GEP
388 GEPI->eraseFromParent();
391 // Finally, delete the Alloca instruction
392 AI->eraseFromParent();
397 /// isSafeElementUse - Check to see if this use is an allowed use for a
398 /// getelementptr instruction of an array aggregate allocation. isFirstElt
399 /// indicates whether Ptr is known to the start of the aggregate.
401 void SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
403 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
405 Instruction *User = cast<Instruction>(*I);
406 switch (User->getOpcode()) {
407 case Instruction::Load: break;
408 case Instruction::Store:
409 // Store is ok if storing INTO the pointer, not storing the pointer
410 if (User->getOperand(0) == Ptr) return MarkUnsafe(Info);
412 case Instruction::GetElementPtr: {
413 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
414 bool AreAllZeroIndices = isFirstElt;
415 if (GEP->getNumOperands() > 1) {
416 if (!isa<ConstantInt>(GEP->getOperand(1)) ||
417 !cast<ConstantInt>(GEP->getOperand(1))->isZero())
418 // Using pointer arithmetic to navigate the array.
419 return MarkUnsafe(Info);
421 if (AreAllZeroIndices)
422 AreAllZeroIndices = GEP->hasAllZeroIndices();
424 isSafeElementUse(GEP, AreAllZeroIndices, AI, Info);
425 if (Info.isUnsafe) return;
428 case Instruction::BitCast:
430 isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI, Info);
431 if (Info.isUnsafe) return;
434 DOUT << " Transformation preventing inst: " << *User;
435 return MarkUnsafe(Info);
436 case Instruction::Call:
437 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
439 isSafeMemIntrinsicOnAllocation(MI, AI, I.getOperandNo(), Info);
440 if (Info.isUnsafe) return;
444 DOUT << " Transformation preventing inst: " << *User;
445 return MarkUnsafe(Info);
447 DOUT << " Transformation preventing inst: " << *User;
448 return MarkUnsafe(Info);
451 return; // All users look ok :)
454 /// AllUsersAreLoads - Return true if all users of this value are loads.
455 static bool AllUsersAreLoads(Value *Ptr) {
456 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
458 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
463 /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
464 /// aggregate allocation.
466 void SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
468 if (BitCastInst *C = dyn_cast<BitCastInst>(User))
469 return isSafeUseOfBitCastedAllocation(C, AI, Info);
471 if (isa<LoadInst>(User))
472 return; // Loads (returning a first class aggregrate) are always rewritable
474 if (isa<StoreInst>(User) && User->getOperand(0) != AI)
475 return; // Store is ok if storing INTO the pointer, not storing the pointer
477 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User);
479 return MarkUnsafe(Info);
481 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
483 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
485 I.getOperand() != Constant::getNullValue(I.getOperand()->getType())) {
486 return MarkUnsafe(Info);
490 if (I == E) return MarkUnsafe(Info); // ran out of GEP indices??
492 bool IsAllZeroIndices = true;
494 // If the first index is a non-constant index into an array, see if we can
495 // handle it as a special case.
496 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
497 if (!isa<ConstantInt>(I.getOperand())) {
498 IsAllZeroIndices = 0;
499 uint64_t NumElements = AT->getNumElements();
501 // If this is an array index and the index is not constant, we cannot
502 // promote... that is unless the array has exactly one or two elements in
503 // it, in which case we CAN promote it, but we have to canonicalize this
504 // out if this is the only problem.
505 if ((NumElements == 1 || NumElements == 2) &&
506 AllUsersAreLoads(GEPI)) {
507 Info.needsCanon = true;
508 return; // Canonicalization required!
510 return MarkUnsafe(Info);
514 // Walk through the GEP type indices, checking the types that this indexes
516 for (; I != E; ++I) {
517 // Ignore struct elements, no extra checking needed for these.
518 if (isa<StructType>(*I))
521 ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
522 if (!IdxVal) return MarkUnsafe(Info);
524 // Are all indices still zero?
525 IsAllZeroIndices &= IdxVal->isZero();
527 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
528 // This GEP indexes an array. Verify that this is an in-range constant
529 // integer. Specifically, consider A[0][i]. We cannot know that the user
530 // isn't doing invalid things like allowing i to index an out-of-range
531 // subscript that accesses A[1]. Because of this, we have to reject SROA
532 // of any accesses into structs where any of the components are variables.
533 if (IdxVal->getZExtValue() >= AT->getNumElements())
534 return MarkUnsafe(Info);
535 } else if (const VectorType *VT = dyn_cast<VectorType>(*I)) {
536 if (IdxVal->getZExtValue() >= VT->getNumElements())
537 return MarkUnsafe(Info);
541 // If there are any non-simple uses of this getelementptr, make sure to reject
543 return isSafeElementUse(GEPI, IsAllZeroIndices, AI, Info);
546 /// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
547 /// intrinsic can be promoted by SROA. At this point, we know that the operand
548 /// of the memintrinsic is a pointer to the beginning of the allocation.
549 void SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
550 unsigned OpNo, AllocaInfo &Info) {
551 // If not constant length, give up.
552 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
553 if (!Length) return MarkUnsafe(Info);
555 // If not the whole aggregate, give up.
556 if (Length->getZExtValue() !=
557 TD->getABITypeSize(AI->getType()->getElementType()))
558 return MarkUnsafe(Info);
560 // We only know about memcpy/memset/memmove.
561 if (!isa<MemCpyInst>(MI) && !isa<MemSetInst>(MI) && !isa<MemMoveInst>(MI))
562 return MarkUnsafe(Info);
564 // Otherwise, we can transform it. Determine whether this is a memcpy/set
565 // into or out of the aggregate.
567 Info.isMemCpyDst = true;
570 Info.isMemCpySrc = true;
574 /// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
576 void SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI,
578 for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
580 if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
581 isSafeUseOfBitCastedAllocation(BCU, AI, Info);
582 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
583 isSafeMemIntrinsicOnAllocation(MI, AI, UI.getOperandNo(), Info);
585 return MarkUnsafe(Info);
587 if (Info.isUnsafe) return;
591 /// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
592 /// to its first element. Transform users of the cast to use the new values
594 void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
595 SmallVector<AllocaInst*, 32> &NewElts) {
596 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
598 Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
600 if (BitCastInst *BCU = dyn_cast<BitCastInst>(*UI)) {
601 RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
603 BCU->eraseFromParent();
607 // Otherwise, must be memcpy/memmove/memset of the entire aggregate. Split
608 // into one per element.
609 MemIntrinsic *MI = dyn_cast<MemIntrinsic>(*UI);
611 // If it's not a mem intrinsic, it must be some other user of a gep of the
612 // first pointer. Just leave these alone.
618 // If this is a memcpy/memmove, construct the other pointer as the
621 if (MemCpyInst *MCI = dyn_cast<MemCpyInst>(MI)) {
622 if (BCInst == MCI->getRawDest())
623 OtherPtr = MCI->getRawSource();
625 assert(BCInst == MCI->getRawSource());
626 OtherPtr = MCI->getRawDest();
628 } else if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
629 if (BCInst == MMI->getRawDest())
630 OtherPtr = MMI->getRawSource();
632 assert(BCInst == MMI->getRawSource());
633 OtherPtr = MMI->getRawDest();
637 // If there is an other pointer, we want to convert it to the same pointer
638 // type as AI has, so we can GEP through it.
640 // It is likely that OtherPtr is a bitcast, if so, remove it.
641 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
642 OtherPtr = BC->getOperand(0);
643 // All zero GEPs are effectively bitcasts.
644 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr))
645 if (GEP->hasAllZeroIndices())
646 OtherPtr = GEP->getOperand(0);
648 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
649 if (BCE->getOpcode() == Instruction::BitCast)
650 OtherPtr = BCE->getOperand(0);
652 // If the pointer is not the right type, insert a bitcast to the right
654 if (OtherPtr->getType() != AI->getType())
655 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
659 // Process each element of the aggregate.
660 Value *TheFn = MI->getOperand(0);
661 const Type *BytePtrTy = MI->getRawDest()->getType();
662 bool SROADest = MI->getRawDest() == BCInst;
664 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
665 // If this is a memcpy/memmove, emit a GEP of the other element address.
668 Value *Idx[2] = { Zero, ConstantInt::get(Type::Int32Ty, i) };
669 OtherElt = GetElementPtrInst::Create(OtherPtr, Idx, Idx + 2,
670 OtherPtr->getNameStr()+"."+utostr(i),
674 Value *EltPtr = NewElts[i];
675 const Type *EltTy =cast<PointerType>(EltPtr->getType())->getElementType();
677 // If we got down to a scalar, insert a load or store as appropriate.
678 if (EltTy->isSingleValueType()) {
679 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
680 Value *Elt = new LoadInst(SROADest ? OtherElt : EltPtr, "tmp",
682 new StoreInst(Elt, SROADest ? EltPtr : OtherElt, MI);
685 assert(isa<MemSetInst>(MI));
687 // If the stored element is zero (common case), just store a null
690 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
692 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
694 // If EltTy is a vector type, get the element type.
695 const Type *ValTy = EltTy;
696 if (const VectorType *VTy = dyn_cast<VectorType>(ValTy))
697 ValTy = VTy->getElementType();
699 // Construct an integer with the right value.
700 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
701 APInt OneVal(EltSize, CI->getZExtValue());
702 APInt TotalVal(OneVal);
704 for (unsigned i = 0; 8*i < EltSize; ++i) {
705 TotalVal = TotalVal.shl(8);
709 // Convert the integer value to the appropriate type.
710 StoreVal = ConstantInt::get(TotalVal);
711 if (isa<PointerType>(ValTy))
712 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
713 else if (ValTy->isFloatingPoint())
714 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
715 assert(StoreVal->getType() == ValTy && "Type mismatch!");
717 // If the requested value was a vector constant, create it.
718 if (EltTy != ValTy) {
719 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
720 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
721 StoreVal = ConstantVector::get(&Elts[0], NumElts);
724 new StoreInst(StoreVal, EltPtr, MI);
727 // Otherwise, if we're storing a byte variable, use a memset call for
732 // Cast the element pointer to BytePtrTy.
733 if (EltPtr->getType() != BytePtrTy)
734 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
736 // Cast the other pointer (if we have one) to BytePtrTy.
737 if (OtherElt && OtherElt->getType() != BytePtrTy)
738 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
741 unsigned EltSize = TD->getABITypeSize(EltTy);
743 // Finally, insert the meminst for this element.
744 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
746 SROADest ? EltPtr : OtherElt, // Dest ptr
747 SROADest ? OtherElt : EltPtr, // Src ptr
748 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
751 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
753 assert(isa<MemSetInst>(MI));
755 EltPtr, MI->getOperand(2), // Dest, Value,
756 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
759 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
763 // Finally, MI is now dead, as we've modified its actions to occur on all of
764 // the elements of the aggregate.
766 MI->eraseFromParent();
770 /// HasPadding - Return true if the specified type has any structure or
771 /// alignment padding, false otherwise.
772 static bool HasPadding(const Type *Ty, const TargetData &TD) {
773 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
774 const StructLayout *SL = TD.getStructLayout(STy);
775 unsigned PrevFieldBitOffset = 0;
776 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
777 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
779 // Padding in sub-elements?
780 if (HasPadding(STy->getElementType(i), TD))
783 // Check to see if there is any padding between this element and the
786 unsigned PrevFieldEnd =
787 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
788 if (PrevFieldEnd < FieldBitOffset)
792 PrevFieldBitOffset = FieldBitOffset;
795 // Check for tail padding.
796 if (unsigned EltCount = STy->getNumElements()) {
797 unsigned PrevFieldEnd = PrevFieldBitOffset +
798 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
799 if (PrevFieldEnd < SL->getSizeInBits())
803 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
804 return HasPadding(ATy->getElementType(), TD);
805 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
806 return HasPadding(VTy->getElementType(), TD);
808 return TD.getTypeSizeInBits(Ty) != TD.getABITypeSizeInBits(Ty);
811 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
812 /// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
813 /// or 1 if safe after canonicalization has been performed.
815 int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
816 // Loop over the use list of the alloca. We can only transform it if all of
817 // the users are safe to transform.
820 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
822 isSafeUseOfAllocation(cast<Instruction>(*I), AI, Info);
824 DOUT << "Cannot transform: " << *AI << " due to user: " << **I;
829 // Okay, we know all the users are promotable. If the aggregate is a memcpy
830 // source and destination, we have to be careful. In particular, the memcpy
831 // could be moving around elements that live in structure padding of the LLVM
832 // types, but may actually be used. In these cases, we refuse to promote the
834 if (Info.isMemCpySrc && Info.isMemCpyDst &&
835 HasPadding(AI->getType()->getElementType(), *TD))
838 // If we require cleanup, return 1, otherwise return 3.
839 return Info.needsCanon ? 1 : 3;
842 /// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified
843 /// allocation, but only if cleaned up, perform the cleanups required.
844 void SROA::CanonicalizeAllocaUsers(AllocationInst *AI) {
845 // At this point, we know that the end result will be SROA'd and promoted, so
846 // we can insert ugly code if required so long as sroa+mem2reg will clean it
848 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
850 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI++);
852 gep_type_iterator I = gep_type_begin(GEPI);
855 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
856 uint64_t NumElements = AT->getNumElements();
858 if (!isa<ConstantInt>(I.getOperand())) {
859 if (NumElements == 1) {
860 GEPI->setOperand(2, Constant::getNullValue(Type::Int32Ty));
862 assert(NumElements == 2 && "Unhandled case!");
863 // All users of the GEP must be loads. At each use of the GEP, insert
864 // two loads of the appropriate indexed GEP and select between them.
865 Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(),
866 Constant::getNullValue(I.getOperand()->getType()),
868 // Insert the new GEP instructions, which are properly indexed.
869 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
870 Indices[1] = Constant::getNullValue(Type::Int32Ty);
871 Value *ZeroIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
874 GEPI->getName()+".0", GEPI);
875 Indices[1] = ConstantInt::get(Type::Int32Ty, 1);
876 Value *OneIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
879 GEPI->getName()+".1", GEPI);
880 // Replace all loads of the variable index GEP with loads from both
881 // indexes and a select.
882 while (!GEPI->use_empty()) {
883 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
884 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
885 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
886 Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI);
887 LI->replaceAllUsesWith(R);
888 LI->eraseFromParent();
890 GEPI->eraseFromParent();
897 /// MergeInType - Add the 'In' type to the accumulated type so far. If the
898 /// types are incompatible, return true, otherwise update Accum and return
901 /// There are three cases we handle here:
902 /// 1) An effectively-integer union, where the pieces are stored into as
903 /// smaller integers (common with byte swap and other idioms).
904 /// 2) A union of vector types of the same size and potentially its elements.
905 /// Here we turn element accesses into insert/extract element operations.
906 /// 3) A union of scalar types, such as int/float or int/pointer. Here we
907 /// merge together into integers, allowing the xform to work with #1 as
909 static bool MergeInType(const Type *In, const Type *&Accum,
910 const TargetData &TD) {
911 // If this is our first type, just use it.
912 const VectorType *PTy;
913 if (Accum == Type::VoidTy || In == Accum) {
915 } else if (In == Type::VoidTy) {
917 } else if (In->isInteger() && Accum->isInteger()) { // integer union.
918 // Otherwise pick whichever type is larger.
919 if (cast<IntegerType>(In)->getBitWidth() >
920 cast<IntegerType>(Accum)->getBitWidth())
922 } else if (isa<PointerType>(In) && isa<PointerType>(Accum)) {
923 // Pointer unions just stay as one of the pointers.
924 } else if (isa<VectorType>(In) || isa<VectorType>(Accum)) {
925 if ((PTy = dyn_cast<VectorType>(Accum)) &&
926 PTy->getElementType() == In) {
927 // Accum is a vector, and we are accessing an element: ok.
928 } else if ((PTy = dyn_cast<VectorType>(In)) &&
929 PTy->getElementType() == Accum) {
930 // In is a vector, and accum is an element: ok, remember In.
932 } else if ((PTy = dyn_cast<VectorType>(In)) && isa<VectorType>(Accum) &&
933 PTy->getBitWidth() == cast<VectorType>(Accum)->getBitWidth()) {
934 // Two vectors of the same size: keep Accum.
936 // Cannot insert an short into a <4 x int> or handle
937 // <2 x int> -> <4 x int>
941 // Pointer/FP/Integer unions merge together as integers.
942 switch (Accum->getTypeID()) {
943 case Type::PointerTyID: Accum = TD.getIntPtrType(); break;
944 case Type::FloatTyID: Accum = Type::Int32Ty; break;
945 case Type::DoubleTyID: Accum = Type::Int64Ty; break;
946 case Type::X86_FP80TyID: return true;
947 case Type::FP128TyID: return true;
948 case Type::PPC_FP128TyID: return true;
950 assert(Accum->isInteger() && "Unknown FP type!");
954 switch (In->getTypeID()) {
955 case Type::PointerTyID: In = TD.getIntPtrType(); break;
956 case Type::FloatTyID: In = Type::Int32Ty; break;
957 case Type::DoubleTyID: In = Type::Int64Ty; break;
958 case Type::X86_FP80TyID: return true;
959 case Type::FP128TyID: return true;
960 case Type::PPC_FP128TyID: return true;
962 assert(In->isInteger() && "Unknown FP type!");
965 return MergeInType(In, Accum, TD);
970 /// getIntAtLeastAsBigAs - Return an integer type that is at least as big as the
971 /// specified type. If there is no suitable type, this returns null.
972 const Type *getIntAtLeastAsBigAs(unsigned NumBits) {
973 if (NumBits > 64) return 0;
974 if (NumBits > 32) return Type::Int64Ty;
975 if (NumBits > 16) return Type::Int32Ty;
976 if (NumBits > 8) return Type::Int16Ty;
980 /// CanConvertToScalar - V is a pointer. If we can convert the pointee to a
981 /// single scalar integer type, return that type. Further, if the use is not
982 /// a completely trivial use that mem2reg could promote, set IsNotTrivial. If
983 /// there are no uses of this pointer, return Type::VoidTy to differentiate from
986 const Type *SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial) {
987 const Type *UsedType = Type::VoidTy; // No uses, no forced type.
988 const PointerType *PTy = cast<PointerType>(V->getType());
990 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
991 Instruction *User = cast<Instruction>(*UI);
993 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
994 // FIXME: Loads of a first class aggregrate value could be converted to a
995 // series of loads and insertvalues
996 if (!LI->getType()->isSingleValueType())
999 if (MergeInType(LI->getType(), UsedType, *TD))
1004 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1005 // Storing the pointer, not into the value?
1006 if (SI->getOperand(0) == V) return 0;
1008 // FIXME: Stores of a first class aggregrate value could be converted to a
1009 // series of extractvalues and stores
1010 if (!SI->getOperand(0)->getType()->isSingleValueType())
1013 // NOTE: We could handle storing of FP imms into integers here!
1015 if (MergeInType(SI->getOperand(0)->getType(), UsedType, *TD))
1019 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
1020 IsNotTrivial = true;
1021 const Type *SubTy = CanConvertToScalar(CI, IsNotTrivial);
1022 if (!SubTy || MergeInType(SubTy, UsedType, *TD)) return 0;
1026 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1027 // Check to see if this is stepping over an element: GEP Ptr, int C
1028 if (GEP->getNumOperands() == 2 && isa<ConstantInt>(GEP->getOperand(1))) {
1029 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
1030 unsigned ElSize = TD->getABITypeSize(PTy->getElementType());
1031 unsigned BitOffset = Idx*ElSize*8;
1032 if (BitOffset > 64 || !isPowerOf2_32(ElSize)) return 0;
1034 IsNotTrivial = true;
1035 const Type *SubElt = CanConvertToScalar(GEP, IsNotTrivial);
1036 if (SubElt == 0) return 0;
1037 if (SubElt != Type::VoidTy && SubElt->isInteger()) {
1039 getIntAtLeastAsBigAs(TD->getABITypeSizeInBits(SubElt)+BitOffset);
1040 if (NewTy == 0 || MergeInType(NewTy, UsedType, *TD)) return 0;
1043 // Cannot handle this!
1047 if (GEP->getNumOperands() == 3 &&
1048 isa<ConstantInt>(GEP->getOperand(1)) &&
1049 isa<ConstantInt>(GEP->getOperand(2)) &&
1050 cast<ConstantInt>(GEP->getOperand(1))->isZero()) {
1051 // We are stepping into an element, e.g. a structure or an array:
1052 // GEP Ptr, i32 0, i32 Cst
1053 const Type *AggTy = PTy->getElementType();
1054 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
1056 if (const ArrayType *ATy = dyn_cast<ArrayType>(AggTy)) {
1057 if (Idx >= ATy->getNumElements()) return 0; // Out of range.
1058 } else if (const VectorType *VectorTy = dyn_cast<VectorType>(AggTy)) {
1059 // Getting an element of the vector.
1060 if (Idx >= VectorTy->getNumElements()) return 0; // Out of range.
1062 // Merge in the vector type.
1063 if (MergeInType(VectorTy, UsedType, *TD)) return 0;
1065 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
1066 if (SubTy == 0) return 0;
1068 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, *TD))
1071 // We'll need to change this to an insert/extract element operation.
1072 IsNotTrivial = true;
1073 continue; // Everything looks ok
1075 } else if (isa<StructType>(AggTy)) {
1076 // Structs are always ok.
1080 const Type *NTy = getIntAtLeastAsBigAs(TD->getABITypeSizeInBits(AggTy));
1081 if (NTy == 0 || MergeInType(NTy, UsedType, *TD)) return 0;
1082 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
1083 if (SubTy == 0) return 0;
1084 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, *TD))
1086 continue; // Everything looks ok
1091 // Cannot handle this!
1098 /// ConvertToScalar - The specified alloca passes the CanConvertToScalar
1099 /// predicate and is non-trivial. Convert it to something that can be trivially
1100 /// promoted into a register by mem2reg.
1101 void SROA::ConvertToScalar(AllocationInst *AI, const Type *ActualTy) {
1102 DOUT << "CONVERT TO SCALAR: " << *AI << " TYPE = "
1103 << *ActualTy << "\n";
1106 BasicBlock *EntryBlock = AI->getParent();
1107 assert(EntryBlock == &EntryBlock->getParent()->getEntryBlock() &&
1108 "Not in the entry block!");
1109 EntryBlock->getInstList().remove(AI); // Take the alloca out of the program.
1111 // Create and insert the alloca.
1112 AllocaInst *NewAI = new AllocaInst(ActualTy, 0, AI->getName(),
1113 EntryBlock->begin());
1114 ConvertUsesToScalar(AI, NewAI, 0);
1119 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
1120 /// directly. This happens when we are converting an "integer union" to a
1121 /// single integer scalar, or when we are converting a "vector union" to a
1122 /// vector with insert/extractelement instructions.
1124 /// Offset is an offset from the original alloca, in bits that need to be
1125 /// shifted to the right. By the end of this, there should be no uses of Ptr.
1126 void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset) {
1127 while (!Ptr->use_empty()) {
1128 Instruction *User = cast<Instruction>(Ptr->use_back());
1130 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1131 Value *NV = ConvertUsesOfLoadToScalar(LI, NewAI, Offset);
1132 LI->replaceAllUsesWith(NV);
1133 LI->eraseFromParent();
1137 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1138 assert(SI->getOperand(0) != Ptr && "Consistency error!");
1140 Value *SV = ConvertUsesOfStoreToScalar(SI, NewAI, Offset);
1141 new StoreInst(SV, NewAI, SI);
1142 SI->eraseFromParent();
1146 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
1147 ConvertUsesToScalar(CI, NewAI, Offset);
1148 CI->eraseFromParent();
1152 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1153 const PointerType *AggPtrTy =
1154 cast<PointerType>(GEP->getOperand(0)->getType());
1155 unsigned AggSizeInBits =
1156 TD->getABITypeSizeInBits(AggPtrTy->getElementType());
1158 // Check to see if this is stepping over an element: GEP Ptr, int C
1159 unsigned NewOffset = Offset;
1160 if (GEP->getNumOperands() == 2) {
1161 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
1162 unsigned BitOffset = Idx*AggSizeInBits;
1164 NewOffset += BitOffset;
1165 ConvertUsesToScalar(GEP, NewAI, NewOffset);
1166 GEP->eraseFromParent();
1170 assert(GEP->getNumOperands() == 3 && "Unsupported operation");
1172 // We know that operand #2 is zero.
1173 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
1174 const Type *AggTy = AggPtrTy->getElementType();
1175 if (const SequentialType *SeqTy = dyn_cast<SequentialType>(AggTy)) {
1176 unsigned ElSizeBits =
1177 TD->getABITypeSizeInBits(SeqTy->getElementType());
1179 NewOffset += ElSizeBits*Idx;
1181 const StructType *STy = cast<StructType>(AggTy);
1182 unsigned EltBitOffset =
1183 TD->getStructLayout(STy)->getElementOffsetInBits(Idx);
1185 NewOffset += EltBitOffset;
1187 ConvertUsesToScalar(GEP, NewAI, NewOffset);
1188 GEP->eraseFromParent();
1192 assert(0 && "Unsupported operation!");
1197 /// ConvertUsesOfLoadToScalar - Convert all of the users the specified load to
1198 /// use the new alloca directly, returning the value that should replace the
1199 /// load. This happens when we are converting an "integer union" to a
1200 /// single integer scalar, or when we are converting a "vector union" to a
1201 /// vector with insert/extractelement instructions.
1203 /// Offset is an offset from the original alloca, in bits that need to be
1204 /// shifted to the right. By the end of this, there should be no uses of Ptr.
1205 Value *SROA::ConvertUsesOfLoadToScalar(LoadInst *LI, AllocaInst *NewAI,
1207 // The load is a bit extract from NewAI shifted right by Offset bits.
1208 Value *NV = new LoadInst(NewAI, LI->getName(), LI);
1210 if (NV->getType() == LI->getType() && Offset == 0) {
1211 // We win, no conversion needed.
1215 // If the result type of the 'union' is a pointer, then this must be ptr->ptr
1216 // cast. Anything else would result in NV being an integer.
1217 if (isa<PointerType>(NV->getType())) {
1218 assert(isa<PointerType>(LI->getType()));
1219 return new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1222 if (const VectorType *VTy = dyn_cast<VectorType>(NV->getType())) {
1223 // If the result alloca is a vector type, this is either an element
1224 // access or a bitcast to another vector type.
1225 if (isa<VectorType>(LI->getType()))
1226 return new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1228 // Otherwise it must be an element access.
1231 unsigned EltSize = TD->getABITypeSizeInBits(VTy->getElementType());
1232 Elt = Offset/EltSize;
1233 Offset -= EltSize*Elt;
1235 NV = new ExtractElementInst(NV, ConstantInt::get(Type::Int32Ty, Elt),
1238 // If we're done, return this element.
1239 if (NV->getType() == LI->getType() && Offset == 0)
1243 const IntegerType *NTy = cast<IntegerType>(NV->getType());
1245 // If this is a big-endian system and the load is narrower than the
1246 // full alloca type, we need to do a shift to get the right bits.
1248 if (TD->isBigEndian()) {
1249 // On big-endian machines, the lowest bit is stored at the bit offset
1250 // from the pointer given by getTypeStoreSizeInBits. This matters for
1251 // integers with a bitwidth that is not a multiple of 8.
1252 ShAmt = TD->getTypeStoreSizeInBits(NTy) -
1253 TD->getTypeStoreSizeInBits(LI->getType()) - Offset;
1258 // Note: we support negative bitwidths (with shl) which are not defined.
1259 // We do this to support (f.e.) loads off the end of a structure where
1260 // only some bits are used.
1261 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
1262 NV = BinaryOperator::CreateLShr(NV,
1263 ConstantInt::get(NV->getType(),ShAmt),
1265 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
1266 NV = BinaryOperator::CreateShl(NV,
1267 ConstantInt::get(NV->getType(),-ShAmt),
1270 // Finally, unconditionally truncate the integer to the right width.
1271 unsigned LIBitWidth = TD->getTypeSizeInBits(LI->getType());
1272 if (LIBitWidth < NTy->getBitWidth())
1273 NV = new TruncInst(NV, IntegerType::get(LIBitWidth),
1276 // If the result is an integer, this is a trunc or bitcast.
1277 if (isa<IntegerType>(LI->getType())) {
1279 } else if (LI->getType()->isFloatingPoint()) {
1280 // Just do a bitcast, we know the sizes match up.
1281 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1283 // Otherwise must be a pointer.
1284 NV = new IntToPtrInst(NV, LI->getType(), LI->getName(), LI);
1286 assert(NV->getType() == LI->getType() && "Didn't convert right?");
1291 /// ConvertUsesOfStoreToScalar - Convert the specified store to a load+store
1292 /// pair of the new alloca directly, returning the value that should be stored
1293 /// to the alloca. This happens when we are converting an "integer union" to a
1294 /// single integer scalar, or when we are converting a "vector union" to a
1295 /// vector with insert/extractelement instructions.
1297 /// Offset is an offset from the original alloca, in bits that need to be
1298 /// shifted to the right. By the end of this, there should be no uses of Ptr.
1299 Value *SROA::ConvertUsesOfStoreToScalar(StoreInst *SI, AllocaInst *NewAI,
1302 // Convert the stored type to the actual type, shift it left to insert
1303 // then 'or' into place.
1304 Value *SV = SI->getOperand(0);
1305 const Type *AllocaType = NewAI->getType()->getElementType();
1306 if (SV->getType() == AllocaType && Offset == 0) {
1308 } else if (const VectorType *PTy = dyn_cast<VectorType>(AllocaType)) {
1309 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1311 // If the result alloca is a vector type, this is either an element
1312 // access or a bitcast to another vector type.
1313 if (isa<VectorType>(SV->getType())) {
1314 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1316 // Must be an element insertion.
1317 unsigned Elt = Offset/TD->getABITypeSizeInBits(PTy->getElementType());
1318 SV = InsertElementInst::Create(Old, SV,
1319 ConstantInt::get(Type::Int32Ty, Elt),
1322 } else if (isa<PointerType>(AllocaType)) {
1323 // If the alloca type is a pointer, then all the elements must be
1325 if (SV->getType() != AllocaType)
1326 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1328 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1330 // If SV is a float, convert it to the appropriate integer type.
1331 // If it is a pointer, do the same, and also handle ptr->ptr casts
1333 unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1334 unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1335 unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1336 unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
1337 if (SV->getType()->isFloatingPoint())
1338 SV = new BitCastInst(SV, IntegerType::get(SrcWidth),
1340 else if (isa<PointerType>(SV->getType()))
1341 SV = new PtrToIntInst(SV, TD->getIntPtrType(), SV->getName(), SI);
1343 // Always zero extend the value if needed.
1344 if (SV->getType() != AllocaType)
1345 SV = new ZExtInst(SV, AllocaType, SV->getName(), SI);
1347 // If this is a big-endian system and the store is narrower than the
1348 // full alloca type, we need to do a shift to get the right bits.
1350 if (TD->isBigEndian()) {
1351 // On big-endian machines, the lowest bit is stored at the bit offset
1352 // from the pointer given by getTypeStoreSizeInBits. This matters for
1353 // integers with a bitwidth that is not a multiple of 8.
1354 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
1359 // Note: we support negative bitwidths (with shr) which are not defined.
1360 // We do this to support (f.e.) stores off the end of a structure where
1361 // only some bits in the structure are set.
1362 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1363 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1364 SV = BinaryOperator::CreateShl(SV,
1365 ConstantInt::get(SV->getType(), ShAmt),
1368 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1369 SV = BinaryOperator::CreateLShr(SV,
1370 ConstantInt::get(SV->getType(),-ShAmt),
1372 Mask = Mask.lshr(ShAmt);
1375 // Mask out the bits we are about to insert from the old value, and or
1377 if (SrcWidth != DestWidth) {
1378 assert(DestWidth > SrcWidth);
1379 Old = BinaryOperator::CreateAnd(Old, ConstantInt::get(~Mask),
1380 Old->getName()+".mask", SI);
1381 SV = BinaryOperator::CreateOr(Old, SV, SV->getName()+".ins", SI);
1389 /// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1390 /// some part of a constant global variable. This intentionally only accepts
1391 /// constant expressions because we don't can't rewrite arbitrary instructions.
1392 static bool PointsToConstantGlobal(Value *V) {
1393 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1394 return GV->isConstant();
1395 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1396 if (CE->getOpcode() == Instruction::BitCast ||
1397 CE->getOpcode() == Instruction::GetElementPtr)
1398 return PointsToConstantGlobal(CE->getOperand(0));
1402 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1403 /// pointer to an alloca. Ignore any reads of the pointer, return false if we
1404 /// see any stores or other unknown uses. If we see pointer arithmetic, keep
1405 /// track of whether it moves the pointer (with isOffset) but otherwise traverse
1406 /// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1407 /// the alloca, and if the source pointer is a pointer to a constant global, we
1408 /// can optimize this.
1409 static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1411 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1412 if (isa<LoadInst>(*UI)) {
1413 // Ignore loads, they are always ok.
1416 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1417 // If uses of the bitcast are ok, we are ok.
1418 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1422 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1423 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1424 // doesn't, it does.
1425 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1426 isOffset || !GEP->hasAllZeroIndices()))
1431 // If this is isn't our memcpy/memmove, reject it as something we can't
1433 if (!isa<MemCpyInst>(*UI) && !isa<MemMoveInst>(*UI))
1436 // If we already have seen a copy, reject the second one.
1437 if (TheCopy) return false;
1439 // If the pointer has been offset from the start of the alloca, we can't
1440 // safely handle this.
1441 if (isOffset) return false;
1443 // If the memintrinsic isn't using the alloca as the dest, reject it.
1444 if (UI.getOperandNo() != 1) return false;
1446 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1448 // If the source of the memcpy/move is not a constant global, reject it.
1449 if (!PointsToConstantGlobal(MI->getOperand(2)))
1452 // Otherwise, the transform is safe. Remember the copy instruction.
1458 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1459 /// modified by a copy from a constant global. If we can prove this, we can
1460 /// replace any uses of the alloca with uses of the global directly.
1461 Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocationInst *AI) {
1462 Instruction *TheCopy = 0;
1463 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))