1 //===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This transformation implements the well known scalar replacement of
11 // aggregates transformation. This xform breaks up alloca instructions of
12 // aggregate type (structure or array) into individual alloca instructions for
13 // each member (if possible). Then, if possible, it transforms the individual
14 // alloca instructions into nice clean scalar SSA form.
16 // This combines a simple SRoA algorithm with the Mem2Reg algorithm because
17 // often interact, especially for C++ programs. As such, iterating between
18 // SRoA, then Mem2Reg until we run out of things to promote works well.
20 //===----------------------------------------------------------------------===//
22 #define DEBUG_TYPE "scalarrepl"
23 #include "llvm/Transforms/Scalar.h"
24 #include "llvm/Constants.h"
25 #include "llvm/DerivedTypes.h"
26 #include "llvm/Function.h"
27 #include "llvm/GlobalVariable.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/IntrinsicInst.h"
30 #include "llvm/Pass.h"
31 #include "llvm/Analysis/Dominators.h"
32 #include "llvm/Target/TargetData.h"
33 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/GetElementPtrTypeIterator.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Compiler.h"
38 #include "llvm/ADT/SmallVector.h"
39 #include "llvm/ADT/Statistic.h"
40 #include "llvm/ADT/StringExtras.h"
43 STATISTIC(NumReplaced, "Number of allocas broken up");
44 STATISTIC(NumPromoted, "Number of allocas promoted");
45 STATISTIC(NumConverted, "Number of aggregates converted to scalar");
46 STATISTIC(NumGlobals, "Number of allocas copied from constant global");
49 struct VISIBILITY_HIDDEN SROA : public FunctionPass {
50 static char ID; // Pass identification, replacement for typeid
51 explicit SROA(signed T = -1) : FunctionPass(&ID) {
58 bool runOnFunction(Function &F);
60 bool performScalarRepl(Function &F);
61 bool performPromotion(Function &F);
63 // getAnalysisUsage - This pass does not require any passes, but we know it
64 // will not alter the CFG, so say so.
65 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
66 AU.addRequired<DominatorTree>();
67 AU.addRequired<DominanceFrontier>();
68 AU.addRequired<TargetData>();
75 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
76 /// information about the uses. All these fields are initialized to false
77 /// and set to true when something is learned.
79 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
82 /// needsCanon - This is set to true if there is some use of the alloca
83 /// that requires canonicalization.
86 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
89 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
93 : isUnsafe(false), needsCanon(false),
94 isMemCpySrc(false), isMemCpyDst(false) {}
99 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
101 int isSafeAllocaToScalarRepl(AllocationInst *AI);
103 void isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
105 void isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
107 void isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
108 unsigned OpNo, AllocaInfo &Info);
109 void isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI,
112 void DoScalarReplacement(AllocationInst *AI,
113 std::vector<AllocationInst*> &WorkList);
114 void CanonicalizeAllocaUsers(AllocationInst *AI);
115 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
117 void RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
118 SmallVector<AllocaInst*, 32> &NewElts);
120 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
122 SmallVector<AllocaInst*, 32> &NewElts);
123 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocationInst *AI,
124 SmallVector<AllocaInst*, 32> &NewElts);
126 const Type *CanConvertToScalar(Value *V, bool &IsNotTrivial);
127 void ConvertToScalar(AllocationInst *AI, const Type *Ty);
128 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset);
129 Value *ConvertUsesOfLoadToScalar(LoadInst *LI, AllocaInst *NewAI,
131 Value *ConvertUsesOfStoreToScalar(StoreInst *SI, AllocaInst *NewAI,
133 static Instruction *isOnlyCopiedFromConstantGlobal(AllocationInst *AI);
138 static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
140 // Public interface to the ScalarReplAggregates pass
141 FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
142 return new SROA(Threshold);
146 bool SROA::runOnFunction(Function &F) {
147 TD = &getAnalysis<TargetData>();
149 bool Changed = performPromotion(F);
151 bool LocalChange = performScalarRepl(F);
152 if (!LocalChange) break; // No need to repromote if no scalarrepl
154 LocalChange = performPromotion(F);
155 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
162 bool SROA::performPromotion(Function &F) {
163 std::vector<AllocaInst*> Allocas;
164 DominatorTree &DT = getAnalysis<DominatorTree>();
165 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
167 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
169 bool Changed = false;
174 // Find allocas that are safe to promote, by looking at all instructions in
176 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
177 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
178 if (isAllocaPromotable(AI))
179 Allocas.push_back(AI);
181 if (Allocas.empty()) break;
183 PromoteMemToReg(Allocas, DT, DF);
184 NumPromoted += Allocas.size();
191 /// getNumSAElements - Return the number of elements in the specific struct or
193 static uint64_t getNumSAElements(const Type *T) {
194 if (const StructType *ST = dyn_cast<StructType>(T))
195 return ST->getNumElements();
196 return cast<ArrayType>(T)->getNumElements();
199 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
200 // which runs on all of the malloc/alloca instructions in the function, removing
201 // them if they are only used by getelementptr instructions.
203 bool SROA::performScalarRepl(Function &F) {
204 std::vector<AllocationInst*> WorkList;
206 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
207 BasicBlock &BB = F.getEntryBlock();
208 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
209 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
210 WorkList.push_back(A);
212 // Process the worklist
213 bool Changed = false;
214 while (!WorkList.empty()) {
215 AllocationInst *AI = WorkList.back();
218 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
219 // with unused elements.
220 if (AI->use_empty()) {
221 AI->eraseFromParent();
225 // If we can turn this aggregate value (potentially with casts) into a
226 // simple scalar value that can be mem2reg'd into a register value.
227 bool IsNotTrivial = false;
228 if (const Type *ActualType = CanConvertToScalar(AI, IsNotTrivial))
229 if (IsNotTrivial && ActualType != Type::VoidTy) {
230 ConvertToScalar(AI, ActualType);
235 // Check to see if we can perform the core SROA transformation. We cannot
236 // transform the allocation instruction if it is an array allocation
237 // (allocations OF arrays are ok though), and an allocation of a scalar
238 // value cannot be decomposed at all.
239 if (!AI->isArrayAllocation() &&
240 (isa<StructType>(AI->getAllocatedType()) ||
241 isa<ArrayType>(AI->getAllocatedType())) &&
242 AI->getAllocatedType()->isSized() &&
243 // Do not promote any struct whose size is larger than "128" bytes.
244 TD->getABITypeSize(AI->getAllocatedType()) < SRThreshold &&
245 // Do not promote any struct into more than "32" separate vars.
246 getNumSAElements(AI->getAllocatedType()) < SRThreshold/4) {
247 // Check that all of the users of the allocation are capable of being
249 switch (isSafeAllocaToScalarRepl(AI)) {
250 default: assert(0 && "Unexpected value!");
251 case 0: // Not safe to scalar replace.
253 case 1: // Safe, but requires cleanup/canonicalizations first
254 CanonicalizeAllocaUsers(AI);
256 case 3: // Safe to scalar replace.
257 DoScalarReplacement(AI, WorkList);
263 // Check to see if this allocation is only modified by a memcpy/memmove from
264 // a constant global. If this is the case, we can change all users to use
265 // the constant global instead. This is commonly produced by the CFE by
266 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
267 // is only subsequently read.
268 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
269 DOUT << "Found alloca equal to global: " << *AI;
270 DOUT << " memcpy = " << *TheCopy;
271 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
272 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
273 TheCopy->eraseFromParent(); // Don't mutate the global.
274 AI->eraseFromParent();
280 // Otherwise, couldn't process this.
286 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
287 /// predicate, do SROA now.
288 void SROA::DoScalarReplacement(AllocationInst *AI,
289 std::vector<AllocationInst*> &WorkList) {
290 DOUT << "Found inst to SROA: " << *AI;
291 SmallVector<AllocaInst*, 32> ElementAllocas;
292 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
293 ElementAllocas.reserve(ST->getNumContainedTypes());
294 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
295 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
297 AI->getName() + "." + utostr(i), AI);
298 ElementAllocas.push_back(NA);
299 WorkList.push_back(NA); // Add to worklist for recursive processing
302 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
303 ElementAllocas.reserve(AT->getNumElements());
304 const Type *ElTy = AT->getElementType();
305 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
306 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
307 AI->getName() + "." + utostr(i), AI);
308 ElementAllocas.push_back(NA);
309 WorkList.push_back(NA); // Add to worklist for recursive processing
313 // Now that we have created the alloca instructions that we want to use,
314 // expand the getelementptr instructions to use them.
316 while (!AI->use_empty()) {
317 Instruction *User = cast<Instruction>(AI->use_back());
318 if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
319 RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
320 BCInst->eraseFromParent();
325 // %res = load { i32, i32 }* %alloc
327 // %load.0 = load i32* %alloc.0
328 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
329 // %load.1 = load i32* %alloc.1
330 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
331 // (Also works for arrays instead of structs)
332 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
333 Value *Insert = UndefValue::get(LI->getType());
334 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
335 Value *Load = new LoadInst(ElementAllocas[i], "load", LI);
336 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
338 LI->replaceAllUsesWith(Insert);
339 LI->eraseFromParent();
344 // store { i32, i32 } %val, { i32, i32 }* %alloc
346 // %val.0 = extractvalue { i32, i32 } %val, 0
347 // store i32 %val.0, i32* %alloc.0
348 // %val.1 = extractvalue { i32, i32 } %val, 1
349 // store i32 %val.1, i32* %alloc.1
350 // (Also works for arrays instead of structs)
351 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
352 Value *Val = SI->getOperand(0);
353 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
354 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
355 new StoreInst(Extract, ElementAllocas[i], SI);
357 SI->eraseFromParent();
361 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
362 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
364 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
366 assert(Idx < ElementAllocas.size() && "Index out of range?");
367 AllocaInst *AllocaToUse = ElementAllocas[Idx];
370 if (GEPI->getNumOperands() == 3) {
371 // Do not insert a new getelementptr instruction with zero indices, only
372 // to have it optimized out later.
373 RepValue = AllocaToUse;
375 // We are indexing deeply into the structure, so we still need a
376 // getelement ptr instruction to finish the indexing. This may be
377 // expanded itself once the worklist is rerun.
379 SmallVector<Value*, 8> NewArgs;
380 NewArgs.push_back(Constant::getNullValue(Type::Int32Ty));
381 NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
382 RepValue = GetElementPtrInst::Create(AllocaToUse, NewArgs.begin(),
383 NewArgs.end(), "", GEPI);
384 RepValue->takeName(GEPI);
387 // If this GEP is to the start of the aggregate, check for memcpys.
388 if (Idx == 0 && GEPI->hasAllZeroIndices())
389 RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas);
391 // Move all of the users over to the new GEP.
392 GEPI->replaceAllUsesWith(RepValue);
393 // Delete the old GEP
394 GEPI->eraseFromParent();
397 // Finally, delete the Alloca instruction
398 AI->eraseFromParent();
403 /// isSafeElementUse - Check to see if this use is an allowed use for a
404 /// getelementptr instruction of an array aggregate allocation. isFirstElt
405 /// indicates whether Ptr is known to the start of the aggregate.
407 void SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
409 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
411 Instruction *User = cast<Instruction>(*I);
412 switch (User->getOpcode()) {
413 case Instruction::Load: break;
414 case Instruction::Store:
415 // Store is ok if storing INTO the pointer, not storing the pointer
416 if (User->getOperand(0) == Ptr) return MarkUnsafe(Info);
418 case Instruction::GetElementPtr: {
419 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
420 bool AreAllZeroIndices = isFirstElt;
421 if (GEP->getNumOperands() > 1) {
422 if (!isa<ConstantInt>(GEP->getOperand(1)) ||
423 !cast<ConstantInt>(GEP->getOperand(1))->isZero())
424 // Using pointer arithmetic to navigate the array.
425 return MarkUnsafe(Info);
427 if (AreAllZeroIndices)
428 AreAllZeroIndices = GEP->hasAllZeroIndices();
430 isSafeElementUse(GEP, AreAllZeroIndices, AI, Info);
431 if (Info.isUnsafe) return;
434 case Instruction::BitCast:
436 isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI, Info);
437 if (Info.isUnsafe) return;
440 DOUT << " Transformation preventing inst: " << *User;
441 return MarkUnsafe(Info);
442 case Instruction::Call:
443 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
445 isSafeMemIntrinsicOnAllocation(MI, AI, I.getOperandNo(), Info);
446 if (Info.isUnsafe) return;
450 DOUT << " Transformation preventing inst: " << *User;
451 return MarkUnsafe(Info);
453 DOUT << " Transformation preventing inst: " << *User;
454 return MarkUnsafe(Info);
457 return; // All users look ok :)
460 /// AllUsersAreLoads - Return true if all users of this value are loads.
461 static bool AllUsersAreLoads(Value *Ptr) {
462 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
464 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
469 /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
470 /// aggregate allocation.
472 void SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
474 if (BitCastInst *C = dyn_cast<BitCastInst>(User))
475 return isSafeUseOfBitCastedAllocation(C, AI, Info);
477 if (isa<LoadInst>(User))
478 return; // Loads (returning a first class aggregrate) are always rewritable
480 if (isa<StoreInst>(User) && User->getOperand(0) != AI)
481 return; // Store is ok if storing INTO the pointer, not storing the pointer
483 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User);
485 return MarkUnsafe(Info);
487 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
489 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
491 I.getOperand() != Constant::getNullValue(I.getOperand()->getType())) {
492 return MarkUnsafe(Info);
496 if (I == E) return MarkUnsafe(Info); // ran out of GEP indices??
498 bool IsAllZeroIndices = true;
500 // If the first index is a non-constant index into an array, see if we can
501 // handle it as a special case.
502 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
503 if (!isa<ConstantInt>(I.getOperand())) {
504 IsAllZeroIndices = 0;
505 uint64_t NumElements = AT->getNumElements();
507 // If this is an array index and the index is not constant, we cannot
508 // promote... that is unless the array has exactly one or two elements in
509 // it, in which case we CAN promote it, but we have to canonicalize this
510 // out if this is the only problem.
511 if ((NumElements == 1 || NumElements == 2) &&
512 AllUsersAreLoads(GEPI)) {
513 Info.needsCanon = true;
514 return; // Canonicalization required!
516 return MarkUnsafe(Info);
520 // Walk through the GEP type indices, checking the types that this indexes
522 for (; I != E; ++I) {
523 // Ignore struct elements, no extra checking needed for these.
524 if (isa<StructType>(*I))
527 ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
528 if (!IdxVal) return MarkUnsafe(Info);
530 // Are all indices still zero?
531 IsAllZeroIndices &= IdxVal->isZero();
533 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
534 // This GEP indexes an array. Verify that this is an in-range constant
535 // integer. Specifically, consider A[0][i]. We cannot know that the user
536 // isn't doing invalid things like allowing i to index an out-of-range
537 // subscript that accesses A[1]. Because of this, we have to reject SROA
538 // of any accesses into structs where any of the components are variables.
539 if (IdxVal->getZExtValue() >= AT->getNumElements())
540 return MarkUnsafe(Info);
541 } else if (const VectorType *VT = dyn_cast<VectorType>(*I)) {
542 if (IdxVal->getZExtValue() >= VT->getNumElements())
543 return MarkUnsafe(Info);
547 // If there are any non-simple uses of this getelementptr, make sure to reject
549 return isSafeElementUse(GEPI, IsAllZeroIndices, AI, Info);
552 /// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
553 /// intrinsic can be promoted by SROA. At this point, we know that the operand
554 /// of the memintrinsic is a pointer to the beginning of the allocation.
555 void SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
556 unsigned OpNo, AllocaInfo &Info) {
557 // If not constant length, give up.
558 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
559 if (!Length) return MarkUnsafe(Info);
561 // If not the whole aggregate, give up.
562 if (Length->getZExtValue() !=
563 TD->getABITypeSize(AI->getType()->getElementType()))
564 return MarkUnsafe(Info);
566 // We only know about memcpy/memset/memmove.
567 if (!isa<MemCpyInst>(MI) && !isa<MemSetInst>(MI) && !isa<MemMoveInst>(MI))
568 return MarkUnsafe(Info);
570 // Otherwise, we can transform it. Determine whether this is a memcpy/set
571 // into or out of the aggregate.
573 Info.isMemCpyDst = true;
576 Info.isMemCpySrc = true;
580 /// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
582 void SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI,
584 for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
586 if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
587 isSafeUseOfBitCastedAllocation(BCU, AI, Info);
588 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
589 isSafeMemIntrinsicOnAllocation(MI, AI, UI.getOperandNo(), Info);
590 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
591 // If storing the entire alloca in one chunk through a bitcasted pointer
592 // to integer, we can transform it. This happens (for example) when you
593 // cast a {i32,i32}* to i64* and store through it. This is similar to the
594 // memcpy case and occurs in various "byval" cases and emulated memcpys.
595 if (isa<IntegerType>(SI->getOperand(0)->getType()) &&
596 TD->getABITypeSize(SI->getOperand(0)->getType()) ==
597 TD->getABITypeSize(AI->getType()->getElementType())) {
598 Info.isMemCpyDst = true;
601 return MarkUnsafe(Info);
603 return MarkUnsafe(Info);
605 if (Info.isUnsafe) return;
609 /// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
610 /// to its first element. Transform users of the cast to use the new values
612 void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
613 SmallVector<AllocaInst*, 32> &NewElts) {
614 Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
616 Instruction *User = cast<Instruction>(*UI++);
617 if (BitCastInst *BCU = dyn_cast<BitCastInst>(User)) {
618 RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
619 if (BCU->use_empty()) BCU->eraseFromParent();
623 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
624 // This must be memcpy/memmove/memset of the entire aggregate.
625 // Split into one per element.
626 RewriteMemIntrinUserOfAlloca(MI, BCInst, AI, NewElts);
630 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
631 // This must be a store of the entire alloca from an integer.
632 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
636 // Otherwise it must be some other user of a gep of the first pointer. Just
637 // leave these alone.
642 /// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
643 /// Rewrite it to copy or set the elements of the scalarized memory.
644 void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
646 SmallVector<AllocaInst*, 32> &NewElts) {
648 // If this is a memcpy/memmove, construct the other pointer as the
651 if (MemCpyInst *MCI = dyn_cast<MemCpyInst>(MI)) {
652 if (BCInst == MCI->getRawDest())
653 OtherPtr = MCI->getRawSource();
655 assert(BCInst == MCI->getRawSource());
656 OtherPtr = MCI->getRawDest();
658 } else if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
659 if (BCInst == MMI->getRawDest())
660 OtherPtr = MMI->getRawSource();
662 assert(BCInst == MMI->getRawSource());
663 OtherPtr = MMI->getRawDest();
667 // If there is an other pointer, we want to convert it to the same pointer
668 // type as AI has, so we can GEP through it safely.
670 // It is likely that OtherPtr is a bitcast, if so, remove it.
671 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
672 OtherPtr = BC->getOperand(0);
673 // All zero GEPs are effectively bitcasts.
674 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr))
675 if (GEP->hasAllZeroIndices())
676 OtherPtr = GEP->getOperand(0);
678 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
679 if (BCE->getOpcode() == Instruction::BitCast)
680 OtherPtr = BCE->getOperand(0);
682 // If the pointer is not the right type, insert a bitcast to the right
684 if (OtherPtr->getType() != AI->getType())
685 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
689 // Process each element of the aggregate.
690 Value *TheFn = MI->getOperand(0);
691 const Type *BytePtrTy = MI->getRawDest()->getType();
692 bool SROADest = MI->getRawDest() == BCInst;
694 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
696 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
697 // If this is a memcpy/memmove, emit a GEP of the other element address.
700 Value *Idx[2] = { Zero, ConstantInt::get(Type::Int32Ty, i) };
701 OtherElt = GetElementPtrInst::Create(OtherPtr, Idx, Idx + 2,
702 OtherPtr->getNameStr()+"."+utostr(i),
706 Value *EltPtr = NewElts[i];
707 const Type *EltTy =cast<PointerType>(EltPtr->getType())->getElementType();
709 // If we got down to a scalar, insert a load or store as appropriate.
710 if (EltTy->isSingleValueType()) {
711 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
712 Value *Elt = new LoadInst(SROADest ? OtherElt : EltPtr, "tmp",
714 new StoreInst(Elt, SROADest ? EltPtr : OtherElt, MI);
717 assert(isa<MemSetInst>(MI));
719 // If the stored element is zero (common case), just store a null
722 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
724 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
726 // If EltTy is a vector type, get the element type.
727 const Type *ValTy = EltTy;
728 if (const VectorType *VTy = dyn_cast<VectorType>(ValTy))
729 ValTy = VTy->getElementType();
731 // Construct an integer with the right value.
732 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
733 APInt OneVal(EltSize, CI->getZExtValue());
734 APInt TotalVal(OneVal);
736 for (unsigned i = 0; 8*i < EltSize; ++i) {
737 TotalVal = TotalVal.shl(8);
741 // Convert the integer value to the appropriate type.
742 StoreVal = ConstantInt::get(TotalVal);
743 if (isa<PointerType>(ValTy))
744 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
745 else if (ValTy->isFloatingPoint())
746 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
747 assert(StoreVal->getType() == ValTy && "Type mismatch!");
749 // If the requested value was a vector constant, create it.
750 if (EltTy != ValTy) {
751 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
752 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
753 StoreVal = ConstantVector::get(&Elts[0], NumElts);
756 new StoreInst(StoreVal, EltPtr, MI);
759 // Otherwise, if we're storing a byte variable, use a memset call for
763 // Cast the element pointer to BytePtrTy.
764 if (EltPtr->getType() != BytePtrTy)
765 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
767 // Cast the other pointer (if we have one) to BytePtrTy.
768 if (OtherElt && OtherElt->getType() != BytePtrTy)
769 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
772 unsigned EltSize = TD->getABITypeSize(EltTy);
774 // Finally, insert the meminst for this element.
775 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
777 SROADest ? EltPtr : OtherElt, // Dest ptr
778 SROADest ? OtherElt : EltPtr, // Src ptr
779 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
782 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
784 assert(isa<MemSetInst>(MI));
786 EltPtr, MI->getOperand(2), // Dest, Value,
787 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
790 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
793 MI->eraseFromParent();
796 /// RewriteStoreUserOfWholeAlloca - We found an store of an integer that
797 /// overwrites the entire allocation. Extract out the pieces of the stored
798 /// integer and store them individually.
799 void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI,
801 SmallVector<AllocaInst*, 32> &NewElts){
802 // Extract each element out of the integer according to its structure offset
803 // and store the element value to the individual alloca.
804 Value *SrcVal = SI->getOperand(0);
805 const Type *AllocaEltTy = AI->getType()->getElementType();
806 uint64_t AllocaSizeBits = TD->getABITypeSizeInBits(AllocaEltTy);
808 // If this isn't a store of an integer to the whole alloca, it may be a store
809 // to the first element. Just ignore the store in this case and normal SROA
811 if (!isa<IntegerType>(SrcVal->getType()) ||
812 TD->getABITypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
815 DOUT << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << *SI;
817 // There are two forms here: AI could be an array or struct. Both cases
818 // have different ways to compute the element offset.
819 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
820 const StructLayout *Layout = TD->getStructLayout(EltSTy);
822 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
823 // Get the number of bits to shift SrcVal to get the value.
824 const Type *FieldTy = EltSTy->getElementType(i);
825 uint64_t Shift = Layout->getElementOffsetInBits(i);
827 if (TD->isBigEndian())
828 Shift = AllocaSizeBits-Shift-TD->getABITypeSizeInBits(FieldTy);
830 Value *EltVal = SrcVal;
832 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
833 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
834 "sroa.store.elt", SI);
837 // Truncate down to an integer of the right size.
838 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
839 if (FieldSizeBits != AllocaSizeBits)
840 EltVal = new TruncInst(EltVal, IntegerType::get(FieldSizeBits), "", SI);
841 Value *DestField = NewElts[i];
842 if (EltVal->getType() == FieldTy) {
843 // Storing to an integer field of this size, just do it.
844 } else if (FieldTy->isFloatingPoint() || isa<VectorType>(FieldTy)) {
845 // Bitcast to the right element type (for fp/vector values).
846 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
848 // Otherwise, bitcast the dest pointer (for aggregates).
849 DestField = new BitCastInst(DestField,
850 PointerType::getUnqual(EltVal->getType()),
853 new StoreInst(EltVal, DestField, SI);
857 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
858 const Type *ArrayEltTy = ATy->getElementType();
859 uint64_t ElementOffset = TD->getABITypeSizeInBits(ArrayEltTy);
860 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
864 if (TD->isBigEndian())
865 Shift = AllocaSizeBits-ElementOffset;
869 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
871 Value *EltVal = SrcVal;
873 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
874 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
875 "sroa.store.elt", SI);
878 // Truncate down to an integer of the right size.
879 if (ElementSizeBits != AllocaSizeBits)
880 EltVal = new TruncInst(EltVal, IntegerType::get(ElementSizeBits),"",SI);
881 Value *DestField = NewElts[i];
882 if (EltVal->getType() == ArrayEltTy) {
883 // Storing to an integer field of this size, just do it.
884 } else if (ArrayEltTy->isFloatingPoint() || isa<VectorType>(ArrayEltTy)) {
885 // Bitcast to the right element type (for fp/vector values).
886 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
888 // Otherwise, bitcast the dest pointer (for aggregates).
889 DestField = new BitCastInst(DestField,
890 PointerType::getUnqual(EltVal->getType()),
893 new StoreInst(EltVal, DestField, SI);
895 if (TD->isBigEndian())
896 Shift -= ElementOffset;
898 Shift += ElementOffset;
902 SI->eraseFromParent();
906 /// HasPadding - Return true if the specified type has any structure or
907 /// alignment padding, false otherwise.
908 static bool HasPadding(const Type *Ty, const TargetData &TD) {
909 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
910 const StructLayout *SL = TD.getStructLayout(STy);
911 unsigned PrevFieldBitOffset = 0;
912 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
913 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
915 // Padding in sub-elements?
916 if (HasPadding(STy->getElementType(i), TD))
919 // Check to see if there is any padding between this element and the
922 unsigned PrevFieldEnd =
923 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
924 if (PrevFieldEnd < FieldBitOffset)
928 PrevFieldBitOffset = FieldBitOffset;
931 // Check for tail padding.
932 if (unsigned EltCount = STy->getNumElements()) {
933 unsigned PrevFieldEnd = PrevFieldBitOffset +
934 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
935 if (PrevFieldEnd < SL->getSizeInBits())
939 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
940 return HasPadding(ATy->getElementType(), TD);
941 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
942 return HasPadding(VTy->getElementType(), TD);
944 return TD.getTypeSizeInBits(Ty) != TD.getABITypeSizeInBits(Ty);
947 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
948 /// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
949 /// or 1 if safe after canonicalization has been performed.
951 int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
952 // Loop over the use list of the alloca. We can only transform it if all of
953 // the users are safe to transform.
956 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
958 isSafeUseOfAllocation(cast<Instruction>(*I), AI, Info);
960 DOUT << "Cannot transform: " << *AI << " due to user: " << **I;
965 // Okay, we know all the users are promotable. If the aggregate is a memcpy
966 // source and destination, we have to be careful. In particular, the memcpy
967 // could be moving around elements that live in structure padding of the LLVM
968 // types, but may actually be used. In these cases, we refuse to promote the
970 if (Info.isMemCpySrc && Info.isMemCpyDst &&
971 HasPadding(AI->getType()->getElementType(), *TD))
974 // If we require cleanup, return 1, otherwise return 3.
975 return Info.needsCanon ? 1 : 3;
978 /// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified
979 /// allocation, but only if cleaned up, perform the cleanups required.
980 void SROA::CanonicalizeAllocaUsers(AllocationInst *AI) {
981 // At this point, we know that the end result will be SROA'd and promoted, so
982 // we can insert ugly code if required so long as sroa+mem2reg will clean it
984 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
986 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI++);
988 gep_type_iterator I = gep_type_begin(GEPI);
991 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
992 uint64_t NumElements = AT->getNumElements();
994 if (!isa<ConstantInt>(I.getOperand())) {
995 if (NumElements == 1) {
996 GEPI->setOperand(2, Constant::getNullValue(Type::Int32Ty));
998 assert(NumElements == 2 && "Unhandled case!");
999 // All users of the GEP must be loads. At each use of the GEP, insert
1000 // two loads of the appropriate indexed GEP and select between them.
1001 Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(),
1002 Constant::getNullValue(I.getOperand()->getType()),
1004 // Insert the new GEP instructions, which are properly indexed.
1005 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
1006 Indices[1] = Constant::getNullValue(Type::Int32Ty);
1007 Value *ZeroIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1010 GEPI->getName()+".0", GEPI);
1011 Indices[1] = ConstantInt::get(Type::Int32Ty, 1);
1012 Value *OneIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1015 GEPI->getName()+".1", GEPI);
1016 // Replace all loads of the variable index GEP with loads from both
1017 // indexes and a select.
1018 while (!GEPI->use_empty()) {
1019 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
1020 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
1021 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
1022 Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI);
1023 LI->replaceAllUsesWith(R);
1024 LI->eraseFromParent();
1026 GEPI->eraseFromParent();
1033 /// MergeInType - Add the 'In' type to the accumulated type so far. If the
1034 /// types are incompatible, return true, otherwise update Accum and return
1037 /// There are three cases we handle here:
1038 /// 1) An effectively-integer union, where the pieces are stored into as
1039 /// smaller integers (common with byte swap and other idioms).
1040 /// 2) A union of vector types of the same size and potentially its elements.
1041 /// Here we turn element accesses into insert/extract element operations.
1042 /// 3) A union of scalar types, such as int/float or int/pointer. Here we
1043 /// merge together into integers, allowing the xform to work with #1 as
1045 static bool MergeInType(const Type *In, const Type *&Accum,
1046 const TargetData &TD) {
1047 // If this is our first type, just use it.
1048 const VectorType *PTy;
1049 if (Accum == Type::VoidTy || In == Accum) {
1051 } else if (In == Type::VoidTy) {
1053 } else if (In->isInteger() && Accum->isInteger()) { // integer union.
1054 // Otherwise pick whichever type is larger.
1055 if (cast<IntegerType>(In)->getBitWidth() >
1056 cast<IntegerType>(Accum)->getBitWidth())
1058 } else if (isa<PointerType>(In) && isa<PointerType>(Accum)) {
1059 // Pointer unions just stay as one of the pointers.
1060 } else if (isa<VectorType>(In) || isa<VectorType>(Accum)) {
1061 if ((PTy = dyn_cast<VectorType>(Accum)) &&
1062 PTy->getElementType() == In) {
1063 // Accum is a vector, and we are accessing an element: ok.
1064 } else if ((PTy = dyn_cast<VectorType>(In)) &&
1065 PTy->getElementType() == Accum) {
1066 // In is a vector, and accum is an element: ok, remember In.
1068 } else if ((PTy = dyn_cast<VectorType>(In)) && isa<VectorType>(Accum) &&
1069 PTy->getBitWidth() == cast<VectorType>(Accum)->getBitWidth()) {
1070 // Two vectors of the same size: keep Accum.
1072 // Cannot insert an short into a <4 x int> or handle
1073 // <2 x int> -> <4 x int>
1077 // Pointer/FP/Integer unions merge together as integers.
1078 switch (Accum->getTypeID()) {
1079 case Type::PointerTyID: Accum = TD.getIntPtrType(); break;
1080 case Type::FloatTyID: Accum = Type::Int32Ty; break;
1081 case Type::DoubleTyID: Accum = Type::Int64Ty; break;
1082 case Type::X86_FP80TyID: return true;
1083 case Type::FP128TyID: return true;
1084 case Type::PPC_FP128TyID: return true;
1086 assert(Accum->isInteger() && "Unknown FP type!");
1090 switch (In->getTypeID()) {
1091 case Type::PointerTyID: In = TD.getIntPtrType(); break;
1092 case Type::FloatTyID: In = Type::Int32Ty; break;
1093 case Type::DoubleTyID: In = Type::Int64Ty; break;
1094 case Type::X86_FP80TyID: return true;
1095 case Type::FP128TyID: return true;
1096 case Type::PPC_FP128TyID: return true;
1098 assert(In->isInteger() && "Unknown FP type!");
1101 return MergeInType(In, Accum, TD);
1106 /// getIntAtLeastAsBigAs - Return an integer type that is at least as big as the
1107 /// specified type. If there is no suitable type, this returns null.
1108 const Type *getIntAtLeastAsBigAs(unsigned NumBits) {
1109 if (NumBits > 64) return 0;
1110 if (NumBits > 32) return Type::Int64Ty;
1111 if (NumBits > 16) return Type::Int32Ty;
1112 if (NumBits > 8) return Type::Int16Ty;
1113 return Type::Int8Ty;
1116 /// CanConvertToScalar - V is a pointer. If we can convert the pointee to a
1117 /// single scalar integer type, return that type. Further, if the use is not
1118 /// a completely trivial use that mem2reg could promote, set IsNotTrivial. If
1119 /// there are no uses of this pointer, return Type::VoidTy to differentiate from
1122 const Type *SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial) {
1123 const Type *UsedType = Type::VoidTy; // No uses, no forced type.
1124 const PointerType *PTy = cast<PointerType>(V->getType());
1126 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1127 Instruction *User = cast<Instruction>(*UI);
1129 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1130 // FIXME: Loads of a first class aggregrate value could be converted to a
1131 // series of loads and insertvalues
1132 if (!LI->getType()->isSingleValueType())
1135 if (MergeInType(LI->getType(), UsedType, *TD))
1140 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1141 // Storing the pointer, not into the value?
1142 if (SI->getOperand(0) == V) return 0;
1144 // FIXME: Stores of a first class aggregrate value could be converted to a
1145 // series of extractvalues and stores
1146 if (!SI->getOperand(0)->getType()->isSingleValueType())
1149 // NOTE: We could handle storing of FP imms into integers here!
1151 if (MergeInType(SI->getOperand(0)->getType(), UsedType, *TD))
1155 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
1156 IsNotTrivial = true;
1157 const Type *SubTy = CanConvertToScalar(CI, IsNotTrivial);
1158 if (!SubTy || MergeInType(SubTy, UsedType, *TD)) return 0;
1162 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1163 // Check to see if this is stepping over an element: GEP Ptr, int C
1164 if (GEP->getNumOperands() == 2 && isa<ConstantInt>(GEP->getOperand(1))) {
1165 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
1166 unsigned ElSize = TD->getABITypeSize(PTy->getElementType());
1167 unsigned BitOffset = Idx*ElSize*8;
1168 if (BitOffset > 64 || !isPowerOf2_32(ElSize)) return 0;
1170 IsNotTrivial = true;
1171 const Type *SubElt = CanConvertToScalar(GEP, IsNotTrivial);
1172 if (SubElt == 0) return 0;
1173 if (SubElt != Type::VoidTy && SubElt->isInteger()) {
1175 getIntAtLeastAsBigAs(TD->getABITypeSizeInBits(SubElt)+BitOffset);
1176 if (NewTy == 0 || MergeInType(NewTy, UsedType, *TD)) return 0;
1179 // Cannot handle this!
1183 if (GEP->getNumOperands() == 3 &&
1184 isa<ConstantInt>(GEP->getOperand(1)) &&
1185 isa<ConstantInt>(GEP->getOperand(2)) &&
1186 cast<ConstantInt>(GEP->getOperand(1))->isZero()) {
1187 // We are stepping into an element, e.g. a structure or an array:
1188 // GEP Ptr, i32 0, i32 Cst
1189 const Type *AggTy = PTy->getElementType();
1190 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
1192 if (const ArrayType *ATy = dyn_cast<ArrayType>(AggTy)) {
1193 if (Idx >= ATy->getNumElements()) return 0; // Out of range.
1194 } else if (const VectorType *VectorTy = dyn_cast<VectorType>(AggTy)) {
1195 // Getting an element of the vector.
1196 if (Idx >= VectorTy->getNumElements()) return 0; // Out of range.
1198 // Merge in the vector type.
1199 if (MergeInType(VectorTy, UsedType, *TD)) return 0;
1201 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
1202 if (SubTy == 0) return 0;
1204 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, *TD))
1207 // We'll need to change this to an insert/extract element operation.
1208 IsNotTrivial = true;
1209 continue; // Everything looks ok
1211 } else if (isa<StructType>(AggTy)) {
1212 // Structs are always ok.
1216 const Type *NTy = getIntAtLeastAsBigAs(TD->getABITypeSizeInBits(AggTy));
1217 if (NTy == 0 || MergeInType(NTy, UsedType, *TD)) return 0;
1218 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
1219 if (SubTy == 0) return 0;
1220 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, *TD))
1222 continue; // Everything looks ok
1227 // Cannot handle this!
1234 /// ConvertToScalar - The specified alloca passes the CanConvertToScalar
1235 /// predicate and is non-trivial. Convert it to something that can be trivially
1236 /// promoted into a register by mem2reg.
1237 void SROA::ConvertToScalar(AllocationInst *AI, const Type *ActualTy) {
1238 DOUT << "CONVERT TO SCALAR: " << *AI << " TYPE = "
1239 << *ActualTy << "\n";
1242 BasicBlock *EntryBlock = AI->getParent();
1243 assert(EntryBlock == &EntryBlock->getParent()->getEntryBlock() &&
1244 "Not in the entry block!");
1245 EntryBlock->getInstList().remove(AI); // Take the alloca out of the program.
1247 // Create and insert the alloca.
1248 AllocaInst *NewAI = new AllocaInst(ActualTy, 0, AI->getName(),
1249 EntryBlock->begin());
1250 ConvertUsesToScalar(AI, NewAI, 0);
1255 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
1256 /// directly. This happens when we are converting an "integer union" to a
1257 /// single integer scalar, or when we are converting a "vector union" to a
1258 /// vector with insert/extractelement instructions.
1260 /// Offset is an offset from the original alloca, in bits that need to be
1261 /// shifted to the right. By the end of this, there should be no uses of Ptr.
1262 void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset) {
1263 while (!Ptr->use_empty()) {
1264 Instruction *User = cast<Instruction>(Ptr->use_back());
1266 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1267 Value *NV = ConvertUsesOfLoadToScalar(LI, NewAI, Offset);
1268 LI->replaceAllUsesWith(NV);
1269 LI->eraseFromParent();
1273 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1274 assert(SI->getOperand(0) != Ptr && "Consistency error!");
1276 Value *SV = ConvertUsesOfStoreToScalar(SI, NewAI, Offset);
1277 new StoreInst(SV, NewAI, SI);
1278 SI->eraseFromParent();
1282 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
1283 ConvertUsesToScalar(CI, NewAI, Offset);
1284 CI->eraseFromParent();
1288 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1289 const PointerType *AggPtrTy =
1290 cast<PointerType>(GEP->getOperand(0)->getType());
1291 unsigned AggSizeInBits =
1292 TD->getABITypeSizeInBits(AggPtrTy->getElementType());
1294 // Check to see if this is stepping over an element: GEP Ptr, int C
1295 unsigned NewOffset = Offset;
1296 if (GEP->getNumOperands() == 2) {
1297 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
1298 unsigned BitOffset = Idx*AggSizeInBits;
1300 NewOffset += BitOffset;
1301 ConvertUsesToScalar(GEP, NewAI, NewOffset);
1302 GEP->eraseFromParent();
1306 assert(GEP->getNumOperands() == 3 && "Unsupported operation");
1308 // We know that operand #2 is zero.
1309 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
1310 const Type *AggTy = AggPtrTy->getElementType();
1311 if (const SequentialType *SeqTy = dyn_cast<SequentialType>(AggTy)) {
1312 unsigned ElSizeBits =
1313 TD->getABITypeSizeInBits(SeqTy->getElementType());
1315 NewOffset += ElSizeBits*Idx;
1317 const StructType *STy = cast<StructType>(AggTy);
1318 unsigned EltBitOffset =
1319 TD->getStructLayout(STy)->getElementOffsetInBits(Idx);
1321 NewOffset += EltBitOffset;
1323 ConvertUsesToScalar(GEP, NewAI, NewOffset);
1324 GEP->eraseFromParent();
1328 assert(0 && "Unsupported operation!");
1333 /// ConvertUsesOfLoadToScalar - Convert all of the users the specified load to
1334 /// use the new alloca directly, returning the value that should replace the
1335 /// load. This happens when we are converting an "integer union" to a
1336 /// single integer scalar, or when we are converting a "vector union" to a
1337 /// vector with insert/extractelement instructions.
1339 /// Offset is an offset from the original alloca, in bits that need to be
1340 /// shifted to the right. By the end of this, there should be no uses of Ptr.
1341 Value *SROA::ConvertUsesOfLoadToScalar(LoadInst *LI, AllocaInst *NewAI,
1343 // The load is a bit extract from NewAI shifted right by Offset bits.
1344 Value *NV = new LoadInst(NewAI, LI->getName(), LI);
1346 if (NV->getType() == LI->getType() && Offset == 0) {
1347 // We win, no conversion needed.
1351 // If the result type of the 'union' is a pointer, then this must be ptr->ptr
1352 // cast. Anything else would result in NV being an integer.
1353 if (isa<PointerType>(NV->getType())) {
1354 assert(isa<PointerType>(LI->getType()));
1355 return new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1358 if (const VectorType *VTy = dyn_cast<VectorType>(NV->getType())) {
1359 // If the result alloca is a vector type, this is either an element
1360 // access or a bitcast to another vector type.
1361 if (isa<VectorType>(LI->getType()))
1362 return new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1364 // Otherwise it must be an element access.
1367 unsigned EltSize = TD->getABITypeSizeInBits(VTy->getElementType());
1368 Elt = Offset/EltSize;
1369 Offset -= EltSize*Elt;
1371 NV = new ExtractElementInst(NV, ConstantInt::get(Type::Int32Ty, Elt),
1374 // If we're done, return this element.
1375 if (NV->getType() == LI->getType() && Offset == 0)
1379 const IntegerType *NTy = cast<IntegerType>(NV->getType());
1381 // If this is a big-endian system and the load is narrower than the
1382 // full alloca type, we need to do a shift to get the right bits.
1384 if (TD->isBigEndian()) {
1385 // On big-endian machines, the lowest bit is stored at the bit offset
1386 // from the pointer given by getTypeStoreSizeInBits. This matters for
1387 // integers with a bitwidth that is not a multiple of 8.
1388 ShAmt = TD->getTypeStoreSizeInBits(NTy) -
1389 TD->getTypeStoreSizeInBits(LI->getType()) - Offset;
1394 // Note: we support negative bitwidths (with shl) which are not defined.
1395 // We do this to support (f.e.) loads off the end of a structure where
1396 // only some bits are used.
1397 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
1398 NV = BinaryOperator::CreateLShr(NV,
1399 ConstantInt::get(NV->getType(),ShAmt),
1401 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
1402 NV = BinaryOperator::CreateShl(NV,
1403 ConstantInt::get(NV->getType(),-ShAmt),
1406 // Finally, unconditionally truncate the integer to the right width.
1407 unsigned LIBitWidth = TD->getTypeSizeInBits(LI->getType());
1408 if (LIBitWidth < NTy->getBitWidth())
1409 NV = new TruncInst(NV, IntegerType::get(LIBitWidth),
1412 // If the result is an integer, this is a trunc or bitcast.
1413 if (isa<IntegerType>(LI->getType())) {
1415 } else if (LI->getType()->isFloatingPoint()) {
1416 // Just do a bitcast, we know the sizes match up.
1417 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1419 // Otherwise must be a pointer.
1420 NV = new IntToPtrInst(NV, LI->getType(), LI->getName(), LI);
1422 assert(NV->getType() == LI->getType() && "Didn't convert right?");
1427 /// ConvertUsesOfStoreToScalar - Convert the specified store to a load+store
1428 /// pair of the new alloca directly, returning the value that should be stored
1429 /// to the alloca. This happens when we are converting an "integer union" to a
1430 /// single integer scalar, or when we are converting a "vector union" to a
1431 /// vector with insert/extractelement instructions.
1433 /// Offset is an offset from the original alloca, in bits that need to be
1434 /// shifted to the right. By the end of this, there should be no uses of Ptr.
1435 Value *SROA::ConvertUsesOfStoreToScalar(StoreInst *SI, AllocaInst *NewAI,
1438 // Convert the stored type to the actual type, shift it left to insert
1439 // then 'or' into place.
1440 Value *SV = SI->getOperand(0);
1441 const Type *AllocaType = NewAI->getType()->getElementType();
1442 if (SV->getType() == AllocaType && Offset == 0) {
1444 } else if (const VectorType *PTy = dyn_cast<VectorType>(AllocaType)) {
1445 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1447 // If the result alloca is a vector type, this is either an element
1448 // access or a bitcast to another vector type.
1449 if (isa<VectorType>(SV->getType())) {
1450 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1452 // Must be an element insertion.
1453 unsigned Elt = Offset/TD->getABITypeSizeInBits(PTy->getElementType());
1454 SV = InsertElementInst::Create(Old, SV,
1455 ConstantInt::get(Type::Int32Ty, Elt),
1458 } else if (isa<PointerType>(AllocaType)) {
1459 // If the alloca type is a pointer, then all the elements must be
1461 if (SV->getType() != AllocaType)
1462 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1464 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1466 // If SV is a float, convert it to the appropriate integer type.
1467 // If it is a pointer, do the same, and also handle ptr->ptr casts
1469 unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1470 unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1471 unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1472 unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
1473 if (SV->getType()->isFloatingPoint())
1474 SV = new BitCastInst(SV, IntegerType::get(SrcWidth),
1476 else if (isa<PointerType>(SV->getType()))
1477 SV = new PtrToIntInst(SV, TD->getIntPtrType(), SV->getName(), SI);
1479 // Always zero extend the value if needed.
1480 if (SV->getType() != AllocaType)
1481 SV = new ZExtInst(SV, AllocaType, SV->getName(), SI);
1483 // If this is a big-endian system and the store is narrower than the
1484 // full alloca type, we need to do a shift to get the right bits.
1486 if (TD->isBigEndian()) {
1487 // On big-endian machines, the lowest bit is stored at the bit offset
1488 // from the pointer given by getTypeStoreSizeInBits. This matters for
1489 // integers with a bitwidth that is not a multiple of 8.
1490 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
1495 // Note: we support negative bitwidths (with shr) which are not defined.
1496 // We do this to support (f.e.) stores off the end of a structure where
1497 // only some bits in the structure are set.
1498 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1499 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1500 SV = BinaryOperator::CreateShl(SV,
1501 ConstantInt::get(SV->getType(), ShAmt),
1504 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1505 SV = BinaryOperator::CreateLShr(SV,
1506 ConstantInt::get(SV->getType(),-ShAmt),
1508 Mask = Mask.lshr(ShAmt);
1511 // Mask out the bits we are about to insert from the old value, and or
1513 if (SrcWidth != DestWidth) {
1514 assert(DestWidth > SrcWidth);
1515 Old = BinaryOperator::CreateAnd(Old, ConstantInt::get(~Mask),
1516 Old->getName()+".mask", SI);
1517 SV = BinaryOperator::CreateOr(Old, SV, SV->getName()+".ins", SI);
1525 /// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1526 /// some part of a constant global variable. This intentionally only accepts
1527 /// constant expressions because we don't can't rewrite arbitrary instructions.
1528 static bool PointsToConstantGlobal(Value *V) {
1529 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1530 return GV->isConstant();
1531 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1532 if (CE->getOpcode() == Instruction::BitCast ||
1533 CE->getOpcode() == Instruction::GetElementPtr)
1534 return PointsToConstantGlobal(CE->getOperand(0));
1538 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1539 /// pointer to an alloca. Ignore any reads of the pointer, return false if we
1540 /// see any stores or other unknown uses. If we see pointer arithmetic, keep
1541 /// track of whether it moves the pointer (with isOffset) but otherwise traverse
1542 /// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1543 /// the alloca, and if the source pointer is a pointer to a constant global, we
1544 /// can optimize this.
1545 static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1547 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1548 if (isa<LoadInst>(*UI)) {
1549 // Ignore loads, they are always ok.
1552 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1553 // If uses of the bitcast are ok, we are ok.
1554 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1558 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1559 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1560 // doesn't, it does.
1561 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1562 isOffset || !GEP->hasAllZeroIndices()))
1567 // If this is isn't our memcpy/memmove, reject it as something we can't
1569 if (!isa<MemCpyInst>(*UI) && !isa<MemMoveInst>(*UI))
1572 // If we already have seen a copy, reject the second one.
1573 if (TheCopy) return false;
1575 // If the pointer has been offset from the start of the alloca, we can't
1576 // safely handle this.
1577 if (isOffset) return false;
1579 // If the memintrinsic isn't using the alloca as the dest, reject it.
1580 if (UI.getOperandNo() != 1) return false;
1582 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1584 // If the source of the memcpy/move is not a constant global, reject it.
1585 if (!PointsToConstantGlobal(MI->getOperand(2)))
1588 // Otherwise, the transform is safe. Remember the copy instruction.
1594 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1595 /// modified by a copy from a constant global. If we can prove this, we can
1596 /// replace any uses of the alloca with uses of the global directly.
1597 Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocationInst *AI) {
1598 Instruction *TheCopy = 0;
1599 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))