blob: 3108bbab145240fb1e718227ecfa01c2f69e987a [file] [log] [blame]
Chris Lattnerfb41a502003-05-27 15:45:27 +00001//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerfb41a502003-05-27 15:45:27 +00009//
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
Chris Lattner5d8a12e2003-09-11 16:45:55 +000013// each member (if possible). Then, if possible, it transforms the individual
14// alloca instructions into nice clean scalar SSA form.
15//
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.
Chris Lattnerfb41a502003-05-27 15:45:27 +000019//
20//===----------------------------------------------------------------------===//
21
Chris Lattner79a42ac2006-12-19 21:40:18 +000022#define DEBUG_TYPE "scalarrepl"
Chris Lattnerfb41a502003-05-27 15:45:27 +000023#include "llvm/Transforms/Scalar.h"
Chris Lattner5d8a12e2003-09-11 16:45:55 +000024#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
Chris Lattnerfb41a502003-05-27 15:45:27 +000026#include "llvm/Function.h"
Misha Brukman2b3387a2004-07-29 17:05:13 +000027#include "llvm/Instructions.h"
Chris Lattner66e6a822007-03-05 07:52:57 +000028#include "llvm/IntrinsicInst.h"
29#include "llvm/Pass.h"
Chris Lattner5d8a12e2003-09-11 16:45:55 +000030#include "llvm/Analysis/Dominators.h"
31#include "llvm/Target/TargetData.h"
32#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Chris Lattner996795b2006-06-28 23:17:24 +000033#include "llvm/Support/Debug.h"
Chris Lattner3b0a62d2005-12-12 07:19:13 +000034#include "llvm/Support/GetElementPtrTypeIterator.h"
35#include "llvm/Support/MathExtras.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000036#include "llvm/Support/Compiler.h"
Chris Lattnera7315132007-02-12 22:56:41 +000037#include "llvm/ADT/SmallVector.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000038#include "llvm/ADT/Statistic.h"
39#include "llvm/ADT/StringExtras.h"
Chris Lattner40d2aeb2003-12-02 17:43:55 +000040using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000041
Chris Lattner79a42ac2006-12-19 21:40:18 +000042STATISTIC(NumReplaced, "Number of allocas broken up");
43STATISTIC(NumPromoted, "Number of allocas promoted");
44STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattnerfb41a502003-05-27 15:45:27 +000045
Chris Lattner79a42ac2006-12-19 21:40:18 +000046namespace {
Chris Lattner996795b2006-06-28 23:17:24 +000047 struct VISIBILITY_HIDDEN SROA : public FunctionPass {
Chris Lattnerfb41a502003-05-27 15:45:27 +000048 bool runOnFunction(Function &F);
49
Chris Lattner5d8a12e2003-09-11 16:45:55 +000050 bool performScalarRepl(Function &F);
51 bool performPromotion(Function &F);
52
Chris Lattnerc8174582003-08-31 00:45:13 +000053 // getAnalysisUsage - This pass does not require any passes, but we know it
54 // will not alter the CFG, so say so.
55 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnera906bac2003-10-05 21:20:13 +000056 AU.addRequired<DominatorTree>();
Chris Lattner5d8a12e2003-09-11 16:45:55 +000057 AU.addRequired<DominanceFrontier>();
58 AU.addRequired<TargetData>();
Chris Lattnerc8174582003-08-31 00:45:13 +000059 AU.setPreservesCFG();
60 }
61
Chris Lattnerfb41a502003-05-27 15:45:27 +000062 private:
Chris Lattner88819122004-11-14 04:24:28 +000063 int isSafeElementUse(Value *Ptr);
Chris Lattner66e6a822007-03-05 07:52:57 +000064 int isSafeUseOfAllocation(Instruction *User, AllocationInst *AI);
65 bool isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI);
Chris Lattner88819122004-11-14 04:24:28 +000066 int isSafeAllocaToScalarRepl(AllocationInst *AI);
67 void CanonicalizeAllocaUsers(AllocationInst *AI);
Chris Lattnerfb41a502003-05-27 15:45:27 +000068 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
Chris Lattner3b0a62d2005-12-12 07:19:13 +000069
Chris Lattner66e6a822007-03-05 07:52:57 +000070 void RewriteBitCastUserOfAlloca(BitCastInst *BCInst, AllocationInst *AI,
71 SmallVector<AllocaInst*, 32> &NewElts);
72
Chris Lattner3b0a62d2005-12-12 07:19:13 +000073 const Type *CanConvertToScalar(Value *V, bool &IsNotTrivial);
74 void ConvertToScalar(AllocationInst *AI, const Type *Ty);
75 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset);
Chris Lattnerfb41a502003-05-27 15:45:27 +000076 };
77
Chris Lattnerc2d3d312006-08-27 22:42:52 +000078 RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
Chris Lattnerfb41a502003-05-27 15:45:27 +000079}
80
Brian Gaeke960707c2003-11-11 22:41:34 +000081// Public interface to the ScalarReplAggregates pass
Chris Lattner3e860842004-09-20 04:43:15 +000082FunctionPass *llvm::createScalarReplAggregatesPass() { return new SROA(); }
Chris Lattnerfb41a502003-05-27 15:45:27 +000083
84
Chris Lattnerfb41a502003-05-27 15:45:27 +000085bool SROA::runOnFunction(Function &F) {
Chris Lattner9a95f2a2003-09-12 15:36:03 +000086 bool Changed = performPromotion(F);
87 while (1) {
88 bool LocalChange = performScalarRepl(F);
89 if (!LocalChange) break; // No need to repromote if no scalarrepl
90 Changed = true;
91 LocalChange = performPromotion(F);
92 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
93 }
Chris Lattner5d8a12e2003-09-11 16:45:55 +000094
95 return Changed;
96}
97
98
99bool SROA::performPromotion(Function &F) {
100 std::vector<AllocaInst*> Allocas;
101 const TargetData &TD = getAnalysis<TargetData>();
Chris Lattnera906bac2003-10-05 21:20:13 +0000102 DominatorTree &DT = getAnalysis<DominatorTree>();
103 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000104
Chris Lattner5dac64f2003-09-20 14:39:18 +0000105 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000106
Chris Lattner9a95f2a2003-09-12 15:36:03 +0000107 bool Changed = false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000108
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000109 while (1) {
110 Allocas.clear();
111
112 // Find allocas that are safe to promote, by looking at all instructions in
113 // the entry node
114 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
115 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
116 if (isAllocaPromotable(AI, TD))
117 Allocas.push_back(AI);
118
119 if (Allocas.empty()) break;
120
Chris Lattnera906bac2003-10-05 21:20:13 +0000121 PromoteMemToReg(Allocas, DT, DF, TD);
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000122 NumPromoted += Allocas.size();
123 Changed = true;
124 }
125
126 return Changed;
127}
128
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000129// performScalarRepl - This algorithm is a simple worklist driven algorithm,
130// which runs on all of the malloc/alloca instructions in the function, removing
131// them if they are only used by getelementptr instructions.
132//
133bool SROA::performScalarRepl(Function &F) {
Chris Lattnerfb41a502003-05-27 15:45:27 +0000134 std::vector<AllocationInst*> WorkList;
135
136 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
Chris Lattner5dac64f2003-09-20 14:39:18 +0000137 BasicBlock &BB = F.getEntryBlock();
Chris Lattnerfb41a502003-05-27 15:45:27 +0000138 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
139 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
140 WorkList.push_back(A);
141
142 // Process the worklist
143 bool Changed = false;
144 while (!WorkList.empty()) {
145 AllocationInst *AI = WorkList.back();
146 WorkList.pop_back();
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000147
Chris Lattnerf171af92006-12-22 23:14:42 +0000148 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
149 // with unused elements.
150 if (AI->use_empty()) {
151 AI->eraseFromParent();
152 continue;
153 }
154
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000155 // If we can turn this aggregate value (potentially with casts) into a
156 // simple scalar value that can be mem2reg'd into a register value.
157 bool IsNotTrivial = false;
158 if (const Type *ActualType = CanConvertToScalar(AI, IsNotTrivial))
Chris Lattnerdae49df2006-04-20 20:48:50 +0000159 if (IsNotTrivial && ActualType != Type::VoidTy) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000160 ConvertToScalar(AI, ActualType);
161 Changed = true;
162 continue;
163 }
Chris Lattnerfb41a502003-05-27 15:45:27 +0000164
165 // We cannot transform the allocation instruction if it is an array
Chris Lattnerc16b2102003-05-27 16:09:27 +0000166 // allocation (allocations OF arrays are ok though), and an allocation of a
167 // scalar value cannot be decomposed at all.
168 //
Chris Lattnerfb41a502003-05-27 15:45:27 +0000169 if (AI->isArrayAllocation() ||
Chris Lattnerc16b2102003-05-27 16:09:27 +0000170 (!isa<StructType>(AI->getAllocatedType()) &&
171 !isa<ArrayType>(AI->getAllocatedType()))) continue;
172
Chris Lattner6e5398d2003-05-30 04:15:41 +0000173 // Check that all of the users of the allocation are capable of being
174 // transformed.
Chris Lattner88819122004-11-14 04:24:28 +0000175 switch (isSafeAllocaToScalarRepl(AI)) {
176 default: assert(0 && "Unexpected value!");
177 case 0: // Not safe to scalar replace.
Chris Lattner6e5398d2003-05-30 04:15:41 +0000178 continue;
Chris Lattner88819122004-11-14 04:24:28 +0000179 case 1: // Safe, but requires cleanup/canonicalizations first
180 CanonicalizeAllocaUsers(AI);
181 case 3: // Safe to scalar replace.
182 break;
183 }
Chris Lattnerfb41a502003-05-27 15:45:27 +0000184
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000185 DOUT << "Found inst to xform: " << *AI;
Chris Lattnerfb41a502003-05-27 15:45:27 +0000186 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000187
Chris Lattner66e6a822007-03-05 07:52:57 +0000188 SmallVector<AllocaInst*, 32> ElementAllocas;
Chris Lattnerfb41a502003-05-27 15:45:27 +0000189 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
190 ElementAllocas.reserve(ST->getNumContainedTypes());
191 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Nate Begeman848622f2005-11-05 09:21:28 +0000192 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
193 AI->getAlignment(),
Chris Lattnerfb41a502003-05-27 15:45:27 +0000194 AI->getName() + "." + utostr(i), AI);
195 ElementAllocas.push_back(NA);
196 WorkList.push_back(NA); // Add to worklist for recursive processing
197 }
198 } else {
Chris Lattner6e5398d2003-05-30 04:15:41 +0000199 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
Chris Lattnerfb41a502003-05-27 15:45:27 +0000200 ElementAllocas.reserve(AT->getNumElements());
201 const Type *ElTy = AT->getElementType();
202 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Nate Begeman848622f2005-11-05 09:21:28 +0000203 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Chris Lattnerfb41a502003-05-27 15:45:27 +0000204 AI->getName() + "." + utostr(i), AI);
205 ElementAllocas.push_back(NA);
206 WorkList.push_back(NA); // Add to worklist for recursive processing
207 }
208 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000209
Chris Lattnerfb41a502003-05-27 15:45:27 +0000210 // Now that we have created the alloca instructions that we want to use,
211 // expand the getelementptr instructions to use them.
212 //
Chris Lattnerb5f8eb82004-06-19 02:02:22 +0000213 while (!AI->use_empty()) {
214 Instruction *User = cast<Instruction>(AI->use_back());
Chris Lattner66e6a822007-03-05 07:52:57 +0000215 if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
216 RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
217 continue;
218 }
219
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000220 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
221 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
Misha Brukmanb1c93172005-04-21 23:48:37 +0000222 unsigned Idx =
Reid Spencere0fc4df2006-10-20 07:07:24 +0000223 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000224
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000225 assert(Idx < ElementAllocas.size() && "Index out of range?");
226 AllocaInst *AllocaToUse = ElementAllocas[Idx];
Misha Brukmanb1c93172005-04-21 23:48:37 +0000227
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000228 Value *RepValue;
229 if (GEPI->getNumOperands() == 3) {
230 // Do not insert a new getelementptr instruction with zero indices, only
231 // to have it optimized out later.
232 RepValue = AllocaToUse;
Chris Lattnerfb41a502003-05-27 15:45:27 +0000233 } else {
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000234 // We are indexing deeply into the structure, so we still need a
235 // getelement ptr instruction to finish the indexing. This may be
236 // expanded itself once the worklist is rerun.
237 //
Chris Lattnera7315132007-02-12 22:56:41 +0000238 SmallVector<Value*, 8> NewArgs;
Reid Spencerc635f472006-12-31 05:48:39 +0000239 NewArgs.push_back(Constant::getNullValue(Type::Int32Ty));
Chris Lattnera7315132007-02-12 22:56:41 +0000240 NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
241 RepValue = new GetElementPtrInst(AllocaToUse, &NewArgs[0],
242 NewArgs.size(), "", GEPI);
Chris Lattner6e0123b2007-02-11 01:23:03 +0000243 RepValue->takeName(GEPI);
Chris Lattnerfb41a502003-05-27 15:45:27 +0000244 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000245
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000246 // Move all of the users over to the new GEP.
247 GEPI->replaceAllUsesWith(RepValue);
248 // Delete the old GEP
249 GEPI->eraseFromParent();
Chris Lattnerfb41a502003-05-27 15:45:27 +0000250 }
251
252 // Finally, delete the Alloca instruction
Chris Lattnerf171af92006-12-22 23:14:42 +0000253 AI->eraseFromParent();
Chris Lattnerc16b2102003-05-27 16:09:27 +0000254 NumReplaced++;
Chris Lattnerfb41a502003-05-27 15:45:27 +0000255 }
256
257 return Changed;
258}
Chris Lattner6e5398d2003-05-30 04:15:41 +0000259
260
Chris Lattner88819122004-11-14 04:24:28 +0000261/// isSafeElementUse - Check to see if this use is an allowed use for a
262/// getelementptr instruction of an array aggregate allocation.
263///
264int SROA::isSafeElementUse(Value *Ptr) {
265 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
266 I != E; ++I) {
267 Instruction *User = cast<Instruction>(*I);
268 switch (User->getOpcode()) {
269 case Instruction::Load: break;
270 case Instruction::Store:
271 // Store is ok if storing INTO the pointer, not storing the pointer
272 if (User->getOperand(0) == Ptr) return 0;
273 break;
274 case Instruction::GetElementPtr: {
275 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
276 if (GEP->getNumOperands() > 1) {
277 if (!isa<Constant>(GEP->getOperand(1)) ||
278 !cast<Constant>(GEP->getOperand(1))->isNullValue())
279 return 0; // Using pointer arithmetic to navigate the array...
280 }
281 if (!isSafeElementUse(GEP)) return 0;
282 break;
283 }
284 default:
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000285 DOUT << " Transformation preventing inst: " << *User;
Chris Lattner88819122004-11-14 04:24:28 +0000286 return 0;
287 }
288 }
289 return 3; // All users look ok :)
290}
291
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000292/// AllUsersAreLoads - Return true if all users of this value are loads.
293static bool AllUsersAreLoads(Value *Ptr) {
294 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
295 I != E; ++I)
296 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
297 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000298 return true;
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000299}
300
Chris Lattner6e5398d2003-05-30 04:15:41 +0000301/// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
302/// aggregate allocation.
303///
Chris Lattner66e6a822007-03-05 07:52:57 +0000304int SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI) {
305 if (BitCastInst *C = dyn_cast<BitCastInst>(User))
306 return 0 && (isSafeUseOfBitCastedAllocation(C, AI) ? 3 : 0);
Chris Lattner88819122004-11-14 04:24:28 +0000307 if (!isa<GetElementPtrInst>(User)) return 0;
Chris Lattner52310702003-11-25 21:09:18 +0000308
309 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
310 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
311
Chris Lattnerfc34f8b2006-03-08 01:05:29 +0000312 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
Chris Lattner52310702003-11-25 21:09:18 +0000313 if (I == E ||
314 I.getOperand() != Constant::getNullValue(I.getOperand()->getType()))
Chris Lattner88819122004-11-14 04:24:28 +0000315 return 0;
Chris Lattner52310702003-11-25 21:09:18 +0000316
317 ++I;
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000318 if (I == E) return 0; // ran out of GEP indices??
Chris Lattner52310702003-11-25 21:09:18 +0000319
320 // If this is a use of an array allocation, do a bit more checking for sanity.
321 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
322 uint64_t NumElements = AT->getNumElements();
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000323
Reid Spencerde46e482006-11-02 20:25:50 +0000324 if (isa<ConstantInt>(I.getOperand())) {
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000325 // Check to make sure that index falls within the array. If not,
326 // something funny is going on, so we won't do the optimization.
327 //
Reid Spencere0fc4df2006-10-20 07:07:24 +0000328 if (cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue() >= NumElements)
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000329 return 0;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000330
Chris Lattnerfc34f8b2006-03-08 01:05:29 +0000331 // We cannot scalar repl this level of the array unless any array
332 // sub-indices are in-range constants. In particular, consider:
333 // A[0][i]. We cannot know that the user isn't doing invalid things like
334 // allowing i to index an out-of-range subscript that accesses A[1].
335 //
336 // Scalar replacing *just* the outer index of the array is probably not
337 // going to be a win anyway, so just give up.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000338 for (++I; I != E && (isa<ArrayType>(*I) || isa<VectorType>(*I)); ++I) {
Chris Lattner4967f6d2006-11-07 22:42:47 +0000339 uint64_t NumElements;
340 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*I))
341 NumElements = SubArrayTy->getNumElements();
342 else
Reid Spencerd84d35b2007-02-15 02:26:10 +0000343 NumElements = cast<VectorType>(*I)->getNumElements();
Chris Lattner4967f6d2006-11-07 22:42:47 +0000344
Chris Lattnerfc34f8b2006-03-08 01:05:29 +0000345 if (!isa<ConstantInt>(I.getOperand())) return 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +0000346 if (cast<ConstantInt>(I.getOperand())->getZExtValue() >= NumElements)
Chris Lattnerfc34f8b2006-03-08 01:05:29 +0000347 return 0;
348 }
349
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000350 } else {
351 // If this is an array index and the index is not constant, we cannot
352 // promote... that is unless the array has exactly one or two elements in
353 // it, in which case we CAN promote it, but we have to canonicalize this
354 // out if this is the only problem.
Chris Lattnerfc34f8b2006-03-08 01:05:29 +0000355 if ((NumElements == 1 || NumElements == 2) &&
356 AllUsersAreLoads(GEPI))
357 return 1; // Canonicalization required!
Chris Lattner88819122004-11-14 04:24:28 +0000358 return 0;
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000359 }
Chris Lattner6e5398d2003-05-30 04:15:41 +0000360 }
Chris Lattner52310702003-11-25 21:09:18 +0000361
362 // If there are any non-simple uses of this getelementptr, make sure to reject
363 // them.
364 return isSafeElementUse(GEPI);
Chris Lattner6e5398d2003-05-30 04:15:41 +0000365}
366
Chris Lattner66e6a822007-03-05 07:52:57 +0000367/// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
368/// are
369bool SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI) {
370 for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
371 UI != E; ++UI) {
372 if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
373 if (!isSafeUseOfBitCastedAllocation(BCU, AI))
374 return false;
375 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
376 // If not constant length, give up.
377 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
378 if (!Length) return false;
379
380 // If not the whole aggregate, give up.
381 const TargetData &TD = getAnalysis<TargetData>();
382 if (Length->getZExtValue() !=
383 TD.getTypeSize(AI->getType()->getElementType()))
384 return false;
385
386 // We only know about memcpy/memset/memmove.
387 if (!isa<MemCpyInst>(MI) && !isa<MemSetInst>(MI) &&
388 !isa<MemMoveInst>(MI))
389 return false;
390 // Otherwise, we can transform it.
391 } else {
392 return false;
393 }
394 }
395 return true;
396}
397
398/// RewriteBitCastUserOfAlloca - BCInst (transitively) casts AI. Transform
399/// users of the cast to use the new values instead.
400void SROA::RewriteBitCastUserOfAlloca(BitCastInst *BCInst, AllocationInst *AI,
401 SmallVector<AllocaInst*, 32> &NewElts) {
402 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
403 const TargetData &TD = getAnalysis<TargetData>();
404 while (!BCInst->use_empty()) {
405 if (BitCastInst *BCU = dyn_cast<BitCastInst>(BCInst->use_back())) {
406 RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
407 continue;
408 }
409
410 // Otherwise, must be memcpy/memmove/memset of the entire aggregate. Split
411 // into one per element.
412 MemIntrinsic *MI = cast<MemIntrinsic>(BCInst->use_back());
413
414 // If this is a memcpy/memmove, construct the other pointer as the
415 // appropriate type.
416 Value *OtherPtr = 0;
417 if (MemCpyInst *MCI = dyn_cast<MemCpyInst>(MI)) {
418 if (BCInst == MCI->getRawDest())
419 OtherPtr = MCI->getRawSource();
420 else {
421 assert(BCInst == MCI->getRawSource());
422 OtherPtr = MCI->getRawDest();
423 }
424 } else if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
425 if (BCInst == MMI->getRawDest())
426 OtherPtr = MMI->getRawSource();
427 else {
428 assert(BCInst == MMI->getRawSource());
429 OtherPtr = MMI->getRawDest();
430 }
431 }
432
433 // If there is an other pointer, we want to convert it to the same pointer
434 // type as AI has, so we can GEP through it.
435 if (OtherPtr) {
436 // It is likely that OtherPtr is a bitcast, if so, remove it.
437 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
438 OtherPtr = BC->getOperand(0);
439 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
440 if (BCE->getOpcode() == Instruction::BitCast)
441 OtherPtr = BCE->getOperand(0);
442
443 // If the pointer is not the right type, insert a bitcast to the right
444 // type.
445 if (OtherPtr->getType() != AI->getType())
446 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
447 MI);
448 }
449
450 // Process each element of the aggregate.
451 Value *TheFn = MI->getOperand(0);
452 const Type *BytePtrTy = MI->getRawDest()->getType();
453 bool SROADest = MI->getRawDest() == BCInst;
454
455 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
456 // If this is a memcpy/memmove, emit a GEP of the other element address.
457 Value *OtherElt = 0;
458 if (OtherPtr) {
459 OtherElt = new GetElementPtrInst(OtherPtr, Zero,
460 ConstantInt::get(Type::Int32Ty, i),
461 OtherPtr->getNameStr()+"."+utostr(i),
462 MI);
Chris Lattner66e6a822007-03-05 07:52:57 +0000463 }
464
465 Value *EltPtr = NewElts[i];
Chris Lattner9f022d52007-03-08 06:36:54 +0000466 const Type *EltTy =cast<PointerType>(EltPtr->getType())->getElementType();
467
468 // If we got down to a scalar, insert a load or store as appropriate.
469 if (EltTy->isFirstClassType()) {
470 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
471 Value *Elt = new LoadInst(SROADest ? OtherElt : EltPtr, "tmp",
472 MI);
473 new StoreInst(Elt, SROADest ? EltPtr : OtherElt, MI);
474 continue;
475 } else {
476 assert(isa<MemSetInst>(MI));
477
478 // If the stored element is zero (common case), just store a null
479 // constant.
480 Constant *StoreVal;
481 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
482 if (CI->isZero()) {
483 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
484 } else {
485 // If EltTy is a packed type, get the element type.
486 const Type *ValTy = EltTy;
487 if (const VectorType *VTy = dyn_cast<VectorType>(ValTy))
488 ValTy = VTy->getElementType();
489
490 // Construct an integer with the right value.
491 unsigned EltSize = TD.getTypeSize(ValTy);
492 APInt OneVal(EltSize*8, CI->getZExtValue());
493 APInt TotalVal(OneVal);
494 // Set each byte.
495 for (unsigned i = 0; i != EltSize-1; ++i) {
496 TotalVal = TotalVal.shl(8);
497 TotalVal |= OneVal;
498 }
499
500 // Convert the integer value to the appropriate type.
501 StoreVal = ConstantInt::get(TotalVal);
502 if (isa<PointerType>(ValTy))
503 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
504 else if (ValTy->isFloatingPoint())
505 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
506 assert(StoreVal->getType() == ValTy && "Type mismatch!");
507
508 // If the requested value was a vector constant, create it.
509 if (EltTy != ValTy) {
510 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
511 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
512 StoreVal = ConstantVector::get(&Elts[0], NumElts);
513 }
514 }
515 new StoreInst(StoreVal, EltPtr, MI);
516 continue;
517 }
518 // Otherwise, if we're storing a byte variable, use a memset call for
519 // this element.
520 }
521 }
Chris Lattner66e6a822007-03-05 07:52:57 +0000522
523 // Cast the element pointer to BytePtrTy.
524 if (EltPtr->getType() != BytePtrTy)
525 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
Chris Lattner9f022d52007-03-08 06:36:54 +0000526
527 // Cast the other pointer (if we have one) to BytePtrTy.
528 if (OtherElt && OtherElt->getType() != BytePtrTy)
529 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
530 MI);
531
532 unsigned EltSize = TD.getTypeSize(EltTy);
533
Chris Lattner66e6a822007-03-05 07:52:57 +0000534 // Finally, insert the meminst for this element.
535 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
536 Value *Ops[] = {
537 SROADest ? EltPtr : OtherElt, // Dest ptr
538 SROADest ? OtherElt : EltPtr, // Src ptr
539 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
540 Zero // Align
541 };
542 new CallInst(TheFn, Ops, 4, "", MI);
Chris Lattner9f022d52007-03-08 06:36:54 +0000543 } else {
544 assert(isa<MemSetInst>(MI));
Chris Lattner66e6a822007-03-05 07:52:57 +0000545 Value *Ops[] = {
546 EltPtr, MI->getOperand(2), // Dest, Value,
547 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
548 Zero // Align
549 };
550 new CallInst(TheFn, Ops, 4, "", MI);
551 }
Chris Lattner9f022d52007-03-08 06:36:54 +0000552 }
Chris Lattner66e6a822007-03-05 07:52:57 +0000553
554 // Finally, MI is now dead, as we've modified its actions to occur on all of
555 // the elements of the aggregate.
556 MI->eraseFromParent();
557 }
558
559 // The cast is dead, remove it.
560 BCInst->eraseFromParent();
561}
562
563
Chris Lattner88819122004-11-14 04:24:28 +0000564/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
565/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
566/// or 1 if safe after canonicalization has been performed.
Chris Lattner6e5398d2003-05-30 04:15:41 +0000567///
Chris Lattner88819122004-11-14 04:24:28 +0000568int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
Chris Lattner6e5398d2003-05-30 04:15:41 +0000569 // Loop over the use list of the alloca. We can only transform it if all of
570 // the users are safe to transform.
571 //
Chris Lattner88819122004-11-14 04:24:28 +0000572 int isSafe = 3;
Chris Lattner6e5398d2003-05-30 04:15:41 +0000573 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
Chris Lattner88819122004-11-14 04:24:28 +0000574 I != E; ++I) {
Chris Lattner66e6a822007-03-05 07:52:57 +0000575 isSafe &= isSafeUseOfAllocation(cast<Instruction>(*I), AI);
Chris Lattner88819122004-11-14 04:24:28 +0000576 if (isSafe == 0) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000577 DOUT << "Cannot transform: " << *AI << " due to user: " << **I;
Chris Lattner88819122004-11-14 04:24:28 +0000578 return 0;
Chris Lattner6e5398d2003-05-30 04:15:41 +0000579 }
Chris Lattner88819122004-11-14 04:24:28 +0000580 }
581 // If we require cleanup, isSafe is now 1, otherwise it is 3.
582 return isSafe;
583}
584
585/// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified
586/// allocation, but only if cleaned up, perform the cleanups required.
587void SROA::CanonicalizeAllocaUsers(AllocationInst *AI) {
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000588 // At this point, we know that the end result will be SROA'd and promoted, so
589 // we can insert ugly code if required so long as sroa+mem2reg will clean it
590 // up.
591 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
592 UI != E; ) {
593 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(*UI++);
Reid Spencer93396382004-11-15 17:29:41 +0000594 gep_type_iterator I = gep_type_begin(GEPI);
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000595 ++I;
Chris Lattner88819122004-11-14 04:24:28 +0000596
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000597 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
598 uint64_t NumElements = AT->getNumElements();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000599
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000600 if (!isa<ConstantInt>(I.getOperand())) {
601 if (NumElements == 1) {
Reid Spencerc635f472006-12-31 05:48:39 +0000602 GEPI->setOperand(2, Constant::getNullValue(Type::Int32Ty));
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000603 } else {
604 assert(NumElements == 2 && "Unhandled case!");
605 // All users of the GEP must be loads. At each use of the GEP, insert
606 // two loads of the appropriate indexed GEP and select between them.
Reid Spencer266e42b2006-12-23 06:05:41 +0000607 Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(),
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000608 Constant::getNullValue(I.getOperand()->getType()),
Reid Spencer266e42b2006-12-23 06:05:41 +0000609 "isone", GEPI);
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000610 // Insert the new GEP instructions, which are properly indexed.
Chris Lattnera7315132007-02-12 22:56:41 +0000611 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
Reid Spencerc635f472006-12-31 05:48:39 +0000612 Indices[1] = Constant::getNullValue(Type::Int32Ty);
Chris Lattnera7315132007-02-12 22:56:41 +0000613 Value *ZeroIdx = new GetElementPtrInst(GEPI->getOperand(0),
614 &Indices[0], Indices.size(),
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000615 GEPI->getName()+".0", GEPI);
Reid Spencerc635f472006-12-31 05:48:39 +0000616 Indices[1] = ConstantInt::get(Type::Int32Ty, 1);
Chris Lattnera7315132007-02-12 22:56:41 +0000617 Value *OneIdx = new GetElementPtrInst(GEPI->getOperand(0),
618 &Indices[0], Indices.size(),
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000619 GEPI->getName()+".1", GEPI);
620 // Replace all loads of the variable index GEP with loads from both
621 // indexes and a select.
622 while (!GEPI->use_empty()) {
623 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
624 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
625 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
626 Value *R = new SelectInst(IsOne, One, Zero, LI->getName(), LI);
627 LI->replaceAllUsesWith(R);
628 LI->eraseFromParent();
629 }
630 GEPI->eraseFromParent();
631 }
632 }
633 }
634 }
Chris Lattner6e5398d2003-05-30 04:15:41 +0000635}
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000636
637/// MergeInType - Add the 'In' type to the accumulated type so far. If the
638/// types are incompatible, return true, otherwise update Accum and return
639/// false.
Chris Lattner3323ce12006-04-14 21:42:41 +0000640///
Chris Lattner8f7b7752006-12-15 07:32:38 +0000641/// There are three cases we handle here:
642/// 1) An effectively-integer union, where the pieces are stored into as
Chris Lattner3323ce12006-04-14 21:42:41 +0000643/// smaller integers (common with byte swap and other idioms).
Chris Lattner8f7b7752006-12-15 07:32:38 +0000644/// 2) A union of vector types of the same size and potentially its elements.
645/// Here we turn element accesses into insert/extract element operations.
646/// 3) A union of scalar types, such as int/float or int/pointer. Here we
647/// merge together into integers, allowing the xform to work with #1 as
648/// well.
Chris Lattner05f82722006-10-08 23:28:04 +0000649static bool MergeInType(const Type *In, const Type *&Accum,
650 const TargetData &TD) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000651 // If this is our first type, just use it.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000652 const VectorType *PTy;
Chris Lattner3323ce12006-04-14 21:42:41 +0000653 if (Accum == Type::VoidTy || In == Accum) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000654 Accum = In;
Chris Lattner8f7b7752006-12-15 07:32:38 +0000655 } else if (In == Type::VoidTy) {
656 // Noop.
Chris Lattner03c49532007-01-15 02:27:26 +0000657 } else if (In->isInteger() && Accum->isInteger()) { // integer union.
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000658 // Otherwise pick whichever type is larger.
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000659 if (cast<IntegerType>(In)->getBitWidth() >
660 cast<IntegerType>(Accum)->getBitWidth())
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000661 Accum = In;
Chris Lattner05f82722006-10-08 23:28:04 +0000662 } else if (isa<PointerType>(In) && isa<PointerType>(Accum)) {
Chris Lattner41b44222006-10-08 23:53:04 +0000663 // Pointer unions just stay as one of the pointers.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000664 } else if (isa<VectorType>(In) || isa<VectorType>(Accum)) {
665 if ((PTy = dyn_cast<VectorType>(Accum)) &&
Chris Lattner8f7b7752006-12-15 07:32:38 +0000666 PTy->getElementType() == In) {
667 // Accum is a vector, and we are accessing an element: ok.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000668 } else if ((PTy = dyn_cast<VectorType>(In)) &&
Chris Lattner8f7b7752006-12-15 07:32:38 +0000669 PTy->getElementType() == Accum) {
670 // In is a vector, and accum is an element: ok, remember In.
671 Accum = In;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000672 } else if ((PTy = dyn_cast<VectorType>(In)) && isa<VectorType>(Accum) &&
673 PTy->getBitWidth() == cast<VectorType>(Accum)->getBitWidth()) {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000674 // Two vectors of the same size: keep Accum.
675 } else {
676 // Cannot insert an short into a <4 x int> or handle
677 // <2 x int> -> <4 x int>
678 return true;
679 }
Chris Lattner7c1dff92006-12-13 02:26:45 +0000680 } else {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000681 // Pointer/FP/Integer unions merge together as integers.
682 switch (Accum->getTypeID()) {
683 case Type::PointerTyID: Accum = TD.getIntPtrType(); break;
Reid Spencerc635f472006-12-31 05:48:39 +0000684 case Type::FloatTyID: Accum = Type::Int32Ty; break;
685 case Type::DoubleTyID: Accum = Type::Int64Ty; break;
Chris Lattner8f7b7752006-12-15 07:32:38 +0000686 default:
Chris Lattner03c49532007-01-15 02:27:26 +0000687 assert(Accum->isInteger() && "Unknown FP type!");
Chris Lattner8f7b7752006-12-15 07:32:38 +0000688 break;
689 }
690
691 switch (In->getTypeID()) {
692 case Type::PointerTyID: In = TD.getIntPtrType(); break;
Reid Spencerc635f472006-12-31 05:48:39 +0000693 case Type::FloatTyID: In = Type::Int32Ty; break;
694 case Type::DoubleTyID: In = Type::Int64Ty; break;
Chris Lattner8f7b7752006-12-15 07:32:38 +0000695 default:
Chris Lattner03c49532007-01-15 02:27:26 +0000696 assert(In->isInteger() && "Unknown FP type!");
Chris Lattner8f7b7752006-12-15 07:32:38 +0000697 break;
698 }
699 return MergeInType(In, Accum, TD);
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000700 }
701 return false;
702}
703
704/// getUIntAtLeastAsBitAs - Return an unsigned integer type that is at least
705/// as big as the specified type. If there is no suitable type, this returns
706/// null.
707const Type *getUIntAtLeastAsBitAs(unsigned NumBits) {
708 if (NumBits > 64) return 0;
Reid Spencerc635f472006-12-31 05:48:39 +0000709 if (NumBits > 32) return Type::Int64Ty;
710 if (NumBits > 16) return Type::Int32Ty;
711 if (NumBits > 8) return Type::Int16Ty;
712 return Type::Int8Ty;
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000713}
714
715/// CanConvertToScalar - V is a pointer. If we can convert the pointee to a
716/// single scalar integer type, return that type. Further, if the use is not
717/// a completely trivial use that mem2reg could promote, set IsNotTrivial. If
718/// there are no uses of this pointer, return Type::VoidTy to differentiate from
719/// failure.
720///
721const Type *SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial) {
722 const Type *UsedType = Type::VoidTy; // No uses, no forced type.
723 const TargetData &TD = getAnalysis<TargetData>();
724 const PointerType *PTy = cast<PointerType>(V->getType());
725
726 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
727 Instruction *User = cast<Instruction>(*UI);
728
729 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner05f82722006-10-08 23:28:04 +0000730 if (MergeInType(LI->getType(), UsedType, TD))
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000731 return 0;
732
733 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Reid Spencer2eadb532007-01-21 00:29:26 +0000734 // Storing the pointer, not into the value?
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000735 if (SI->getOperand(0) == V) return 0;
736
Chris Lattner3323ce12006-04-14 21:42:41 +0000737 // NOTE: We could handle storing of FP imms into integers here!
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000738
Chris Lattner05f82722006-10-08 23:28:04 +0000739 if (MergeInType(SI->getOperand(0)->getType(), UsedType, TD))
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000740 return 0;
Chris Lattner8f7b7752006-12-15 07:32:38 +0000741 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000742 IsNotTrivial = true;
743 const Type *SubTy = CanConvertToScalar(CI, IsNotTrivial);
Chris Lattner05f82722006-10-08 23:28:04 +0000744 if (!SubTy || MergeInType(SubTy, UsedType, TD)) return 0;
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000745 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
746 // Check to see if this is stepping over an element: GEP Ptr, int C
747 if (GEP->getNumOperands() == 2 && isa<ConstantInt>(GEP->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000748 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000749 unsigned ElSize = TD.getTypeSize(PTy->getElementType());
750 unsigned BitOffset = Idx*ElSize*8;
751 if (BitOffset > 64 || !isPowerOf2_32(ElSize)) return 0;
752
753 IsNotTrivial = true;
754 const Type *SubElt = CanConvertToScalar(GEP, IsNotTrivial);
755 if (SubElt == 0) return 0;
Chris Lattner03c49532007-01-15 02:27:26 +0000756 if (SubElt != Type::VoidTy && SubElt->isInteger()) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000757 const Type *NewTy =
Chris Lattner41b44222006-10-08 23:53:04 +0000758 getUIntAtLeastAsBitAs(TD.getTypeSize(SubElt)*8+BitOffset);
Chris Lattner05f82722006-10-08 23:28:04 +0000759 if (NewTy == 0 || MergeInType(NewTy, UsedType, TD)) return 0;
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000760 continue;
761 }
762 } else if (GEP->getNumOperands() == 3 &&
763 isa<ConstantInt>(GEP->getOperand(1)) &&
764 isa<ConstantInt>(GEP->getOperand(2)) &&
765 cast<Constant>(GEP->getOperand(1))->isNullValue()) {
766 // We are stepping into an element, e.g. a structure or an array:
767 // GEP Ptr, int 0, uint C
768 const Type *AggTy = PTy->getElementType();
Reid Spencere0fc4df2006-10-20 07:07:24 +0000769 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000770
771 if (const ArrayType *ATy = dyn_cast<ArrayType>(AggTy)) {
772 if (Idx >= ATy->getNumElements()) return 0; // Out of range.
Reid Spencer09575ba2007-02-15 03:39:18 +0000773 } else if (const VectorType *VectorTy = dyn_cast<VectorType>(AggTy)) {
Chris Lattner3323ce12006-04-14 21:42:41 +0000774 // Getting an element of the packed vector.
Reid Spencer09575ba2007-02-15 03:39:18 +0000775 if (Idx >= VectorTy->getNumElements()) return 0; // Out of range.
Chris Lattner3323ce12006-04-14 21:42:41 +0000776
Reid Spencer09575ba2007-02-15 03:39:18 +0000777 // Merge in the vector type.
778 if (MergeInType(VectorTy, UsedType, TD)) return 0;
Chris Lattner3323ce12006-04-14 21:42:41 +0000779
780 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
781 if (SubTy == 0) return 0;
782
Chris Lattner05f82722006-10-08 23:28:04 +0000783 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
Chris Lattner3323ce12006-04-14 21:42:41 +0000784 return 0;
785
786 // We'll need to change this to an insert/extract element operation.
787 IsNotTrivial = true;
788 continue; // Everything looks ok
789
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000790 } else if (isa<StructType>(AggTy)) {
791 // Structs are always ok.
792 } else {
793 return 0;
794 }
795 const Type *NTy = getUIntAtLeastAsBitAs(TD.getTypeSize(AggTy)*8);
Chris Lattner05f82722006-10-08 23:28:04 +0000796 if (NTy == 0 || MergeInType(NTy, UsedType, TD)) return 0;
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000797 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
798 if (SubTy == 0) return 0;
Chris Lattner05f82722006-10-08 23:28:04 +0000799 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000800 return 0;
801 continue; // Everything looks ok
802 }
803 return 0;
804 } else {
805 // Cannot handle this!
806 return 0;
807 }
808 }
809
810 return UsedType;
811}
812
813/// ConvertToScalar - The specified alloca passes the CanConvertToScalar
814/// predicate and is non-trivial. Convert it to something that can be trivially
815/// promoted into a register by mem2reg.
816void SROA::ConvertToScalar(AllocationInst *AI, const Type *ActualTy) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000817 DOUT << "CONVERT TO SCALAR: " << *AI << " TYPE = "
818 << *ActualTy << "\n";
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000819 ++NumConverted;
820
821 BasicBlock *EntryBlock = AI->getParent();
822 assert(EntryBlock == &EntryBlock->getParent()->front() &&
823 "Not in the entry block!");
824 EntryBlock->getInstList().remove(AI); // Take the alloca out of the program.
825
826 // Create and insert the alloca.
Chris Lattner3323ce12006-04-14 21:42:41 +0000827 AllocaInst *NewAI = new AllocaInst(ActualTy, 0, AI->getName(),
828 EntryBlock->begin());
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000829 ConvertUsesToScalar(AI, NewAI, 0);
830 delete AI;
831}
832
833
834/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
Chris Lattner3323ce12006-04-14 21:42:41 +0000835/// directly. This happens when we are converting an "integer union" to a
836/// single integer scalar, or when we are converting a "vector union" to a
837/// vector with insert/extractelement instructions.
838///
839/// Offset is an offset from the original alloca, in bits that need to be
840/// shifted to the right. By the end of this, there should be no uses of Ptr.
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000841void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000842 bool isVectorInsert = isa<VectorType>(NewAI->getType()->getElementType());
Chris Lattner41b44222006-10-08 23:53:04 +0000843 const TargetData &TD = getAnalysis<TargetData>();
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000844 while (!Ptr->use_empty()) {
845 Instruction *User = cast<Instruction>(Ptr->use_back());
846
847 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
848 // The load is a bit extract from NewAI shifted right by Offset bits.
849 Value *NV = new LoadInst(NewAI, LI->getName(), LI);
Chris Lattner3323ce12006-04-14 21:42:41 +0000850 if (NV->getType() != LI->getType()) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000851 if (const VectorType *PTy = dyn_cast<VectorType>(NV->getType())) {
Reid Spencer09575ba2007-02-15 03:39:18 +0000852 // If the result alloca is a vector type, this is either an element
853 // access or a bitcast to another vector type.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000854 if (isa<VectorType>(LI->getType())) {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000855 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
Chris Lattner216c3022006-12-10 23:56:50 +0000856 } else {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000857 // Must be an element access.
858 unsigned Elt = Offset/(TD.getTypeSize(PTy->getElementType())*8);
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000859 NV = new ExtractElementInst(
860 NV, ConstantInt::get(Type::Int32Ty, Elt), "tmp", LI);
Chris Lattner216c3022006-12-10 23:56:50 +0000861 }
Chris Lattner8f7b7752006-12-15 07:32:38 +0000862 } else if (isa<PointerType>(NV->getType())) {
863 assert(isa<PointerType>(LI->getType()));
864 // Must be ptr->ptr cast. Anything else would result in NV being
865 // an integer.
866 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
867 } else {
Chris Lattner03c49532007-01-15 02:27:26 +0000868 assert(NV->getType()->isInteger() && "Unknown promotion!");
Chris Lattner8f7b7752006-12-15 07:32:38 +0000869 if (Offset && Offset < TD.getTypeSize(NV->getType())*8) {
Reid Spencer0d5f9232007-02-02 14:08:20 +0000870 NV = BinaryOperator::createLShr(NV,
Reid Spencer2341c222007-02-02 02:16:23 +0000871 ConstantInt::get(NV->getType(), Offset),
872 LI->getName(), LI);
Chris Lattner8f7b7752006-12-15 07:32:38 +0000873 }
874
875 // If the result is an integer, this is a trunc or bitcast.
Chris Lattner03c49532007-01-15 02:27:26 +0000876 if (LI->getType()->isInteger()) {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000877 NV = CastInst::createTruncOrBitCast(NV, LI->getType(),
878 LI->getName(), LI);
879 } else if (LI->getType()->isFloatingPoint()) {
880 // If needed, truncate the integer to the appropriate size.
Reid Spencer8f166b02007-01-08 16:32:00 +0000881 if (NV->getType()->getPrimitiveSizeInBits() >
882 LI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000883 switch (LI->getType()->getTypeID()) {
884 default: assert(0 && "Unknown FP type!");
885 case Type::FloatTyID:
Reid Spencerc635f472006-12-31 05:48:39 +0000886 NV = new TruncInst(NV, Type::Int32Ty, LI->getName(), LI);
Chris Lattner8f7b7752006-12-15 07:32:38 +0000887 break;
888 case Type::DoubleTyID:
Reid Spencerc635f472006-12-31 05:48:39 +0000889 NV = new TruncInst(NV, Type::Int64Ty, LI->getName(), LI);
Chris Lattner8f7b7752006-12-15 07:32:38 +0000890 break;
891 }
892 }
893
894 // Then do a bitcast.
895 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
896 } else {
897 // Otherwise must be a pointer.
898 NV = new IntToPtrInst(NV, LI->getType(), LI->getName(), LI);
899 }
Chris Lattner3323ce12006-04-14 21:42:41 +0000900 }
901 }
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000902 LI->replaceAllUsesWith(NV);
903 LI->eraseFromParent();
904 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
905 assert(SI->getOperand(0) != Ptr && "Consistency error!");
906
907 // Convert the stored type to the actual type, shift it left to insert
908 // then 'or' into place.
909 Value *SV = SI->getOperand(0);
Chris Lattner3323ce12006-04-14 21:42:41 +0000910 const Type *AllocaType = NewAI->getType()->getElementType();
911 if (SV->getType() != AllocaType) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000912 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
Chris Lattner3323ce12006-04-14 21:42:41 +0000913
Reid Spencerd84d35b2007-02-15 02:26:10 +0000914 if (const VectorType *PTy = dyn_cast<VectorType>(AllocaType)) {
Reid Spencer09575ba2007-02-15 03:39:18 +0000915 // If the result alloca is a vector type, this is either an element
916 // access or a bitcast to another vector type.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000917 if (isa<VectorType>(SV->getType())) {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000918 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
919 } else {
920 // Must be an element insertion.
921 unsigned Elt = Offset/(TD.getTypeSize(PTy->getElementType())*8);
922 SV = new InsertElementInst(Old, SV,
Reid Spencerc635f472006-12-31 05:48:39 +0000923 ConstantInt::get(Type::Int32Ty, Elt),
Chris Lattner8f7b7752006-12-15 07:32:38 +0000924 "tmp", SI);
925 }
Chris Lattner3323ce12006-04-14 21:42:41 +0000926 } else {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000927 // If SV is a float, convert it to the appropriate integer type.
928 // If it is a pointer, do the same, and also handle ptr->ptr casts
929 // here.
930 switch (SV->getType()->getTypeID()) {
931 default:
932 assert(!SV->getType()->isFloatingPoint() && "Unknown FP type!");
933 break;
934 case Type::FloatTyID:
Reid Spencerc635f472006-12-31 05:48:39 +0000935 SV = new BitCastInst(SV, Type::Int32Ty, SV->getName(), SI);
Chris Lattner8f7b7752006-12-15 07:32:38 +0000936 break;
937 case Type::DoubleTyID:
Reid Spencerc635f472006-12-31 05:48:39 +0000938 SV = new BitCastInst(SV, Type::Int64Ty, SV->getName(), SI);
Chris Lattner8f7b7752006-12-15 07:32:38 +0000939 break;
940 case Type::PointerTyID:
941 if (isa<PointerType>(AllocaType))
942 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
943 else
944 SV = new PtrToIntInst(SV, TD.getIntPtrType(), SV->getName(), SI);
945 break;
946 }
947
948 unsigned SrcSize = TD.getTypeSize(SV->getType())*8;
949
950 // Always zero extend the value if needed.
951 if (SV->getType() != AllocaType)
952 SV = CastInst::createZExtOrBitCast(SV, AllocaType,
953 SV->getName(), SI);
954 if (Offset && Offset < AllocaType->getPrimitiveSizeInBits())
Reid Spencer0d5f9232007-02-02 14:08:20 +0000955 SV = BinaryOperator::createShl(SV,
Reid Spencer2341c222007-02-02 02:16:23 +0000956 ConstantInt::get(SV->getType(), Offset),
957 SV->getName()+".adj", SI);
Chris Lattner3323ce12006-04-14 21:42:41 +0000958 // Mask out the bits we are about to insert from the old value.
Chris Lattner41b44222006-10-08 23:53:04 +0000959 unsigned TotalBits = TD.getTypeSize(SV->getType())*8;
Chris Lattner8f7b7752006-12-15 07:32:38 +0000960 if (TotalBits != SrcSize) {
961 assert(TotalBits > SrcSize);
962 uint64_t Mask = ~(((1ULL << SrcSize)-1) << Offset);
Reid Spencera94d3942007-01-19 21:13:56 +0000963 Mask = Mask & cast<IntegerType>(SV->getType())->getBitMask();
Chris Lattner3323ce12006-04-14 21:42:41 +0000964 Old = BinaryOperator::createAnd(Old,
Reid Spencere0fc4df2006-10-20 07:07:24 +0000965 ConstantInt::get(Old->getType(), Mask),
Chris Lattner3323ce12006-04-14 21:42:41 +0000966 Old->getName()+".mask", SI);
967 SV = BinaryOperator::createOr(Old, SV, SV->getName()+".ins", SI);
968 }
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000969 }
970 }
971 new StoreInst(SV, NewAI, SI);
972 SI->eraseFromParent();
973
974 } else if (CastInst *CI = dyn_cast<CastInst>(User)) {
975 unsigned NewOff = Offset;
976 const TargetData &TD = getAnalysis<TargetData>();
Chris Lattner3323ce12006-04-14 21:42:41 +0000977 if (TD.isBigEndian() && !isVectorInsert) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000978 // Adjust the pointer. For example, storing 16-bits into a 32-bit
979 // alloca with just a cast makes it modify the top 16-bits.
980 const Type *SrcTy = cast<PointerType>(Ptr->getType())->getElementType();
981 const Type *DstTy = cast<PointerType>(CI->getType())->getElementType();
982 int PtrDiffBits = TD.getTypeSize(SrcTy)*8-TD.getTypeSize(DstTy)*8;
983 NewOff += PtrDiffBits;
984 }
985 ConvertUsesToScalar(CI, NewAI, NewOff);
986 CI->eraseFromParent();
987 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
988 const PointerType *AggPtrTy =
989 cast<PointerType>(GEP->getOperand(0)->getType());
990 const TargetData &TD = getAnalysis<TargetData>();
991 unsigned AggSizeInBits = TD.getTypeSize(AggPtrTy->getElementType())*8;
992
993 // Check to see if this is stepping over an element: GEP Ptr, int C
994 unsigned NewOffset = Offset;
995 if (GEP->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000996 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000997 unsigned BitOffset = Idx*AggSizeInBits;
998
Chris Lattner3323ce12006-04-14 21:42:41 +0000999 if (TD.isLittleEndian() || isVectorInsert)
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001000 NewOffset += BitOffset;
1001 else
1002 NewOffset -= BitOffset;
1003
1004 } else if (GEP->getNumOperands() == 3) {
1005 // We know that operand #2 is zero.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001006 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001007 const Type *AggTy = AggPtrTy->getElementType();
1008 if (const SequentialType *SeqTy = dyn_cast<SequentialType>(AggTy)) {
1009 unsigned ElSizeBits = TD.getTypeSize(SeqTy->getElementType())*8;
1010
Chris Lattner3323ce12006-04-14 21:42:41 +00001011 if (TD.isLittleEndian() || isVectorInsert)
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001012 NewOffset += ElSizeBits*Idx;
1013 else
1014 NewOffset += AggSizeInBits-ElSizeBits*(Idx+1);
1015 } else if (const StructType *STy = dyn_cast<StructType>(AggTy)) {
Chris Lattnerc473d8e2007-02-10 19:55:17 +00001016 unsigned EltBitOffset =
1017 TD.getStructLayout(STy)->getElementOffset(Idx)*8;
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001018
Chris Lattner3323ce12006-04-14 21:42:41 +00001019 if (TD.isLittleEndian() || isVectorInsert)
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001020 NewOffset += EltBitOffset;
1021 else {
1022 const PointerType *ElPtrTy = cast<PointerType>(GEP->getType());
1023 unsigned ElSizeBits = TD.getTypeSize(ElPtrTy->getElementType())*8;
1024 NewOffset += AggSizeInBits-(EltBitOffset+ElSizeBits);
1025 }
1026
1027 } else {
1028 assert(0 && "Unsupported operation!");
1029 abort();
1030 }
1031 } else {
1032 assert(0 && "Unsupported operation!");
1033 abort();
1034 }
1035 ConvertUsesToScalar(GEP, NewAI, NewOffset);
1036 GEP->eraseFromParent();
1037 } else {
1038 assert(0 && "Unsupported operation!");
1039 abort();
1040 }
1041 }
1042}