blob: 87cf3e1f4abca726b093b5751cb7bf04c88ed18d [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);
463 if (OtherElt->getType() != BytePtrTy)
464 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
465 MI);
466 }
467
468 Value *EltPtr = NewElts[i];
469 unsigned EltSize =
470 TD.getTypeSize(cast<PointerType>(EltPtr->getType())->getElementType());
471
472 // Cast the element pointer to BytePtrTy.
473 if (EltPtr->getType() != BytePtrTy)
474 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
475
476
477 // Finally, insert the meminst for this element.
478 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
479 Value *Ops[] = {
480 SROADest ? EltPtr : OtherElt, // Dest ptr
481 SROADest ? OtherElt : EltPtr, // Src ptr
482 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
483 Zero // Align
484 };
485 new CallInst(TheFn, Ops, 4, "", MI);
486 } else if (isa<MemSetInst>(MI)) {
487 Value *Ops[] = {
488 EltPtr, MI->getOperand(2), // Dest, Value,
489 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
490 Zero // Align
491 };
492 new CallInst(TheFn, Ops, 4, "", MI);
493 }
494 }
495
496 // Finally, MI is now dead, as we've modified its actions to occur on all of
497 // the elements of the aggregate.
498 MI->eraseFromParent();
499 }
500
501 // The cast is dead, remove it.
502 BCInst->eraseFromParent();
503}
504
505
Chris Lattner88819122004-11-14 04:24:28 +0000506/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
507/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
508/// or 1 if safe after canonicalization has been performed.
Chris Lattner6e5398d2003-05-30 04:15:41 +0000509///
Chris Lattner88819122004-11-14 04:24:28 +0000510int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
Chris Lattner6e5398d2003-05-30 04:15:41 +0000511 // Loop over the use list of the alloca. We can only transform it if all of
512 // the users are safe to transform.
513 //
Chris Lattner88819122004-11-14 04:24:28 +0000514 int isSafe = 3;
Chris Lattner6e5398d2003-05-30 04:15:41 +0000515 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
Chris Lattner88819122004-11-14 04:24:28 +0000516 I != E; ++I) {
Chris Lattner66e6a822007-03-05 07:52:57 +0000517 isSafe &= isSafeUseOfAllocation(cast<Instruction>(*I), AI);
Chris Lattner88819122004-11-14 04:24:28 +0000518 if (isSafe == 0) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000519 DOUT << "Cannot transform: " << *AI << " due to user: " << **I;
Chris Lattner88819122004-11-14 04:24:28 +0000520 return 0;
Chris Lattner6e5398d2003-05-30 04:15:41 +0000521 }
Chris Lattner88819122004-11-14 04:24:28 +0000522 }
523 // If we require cleanup, isSafe is now 1, otherwise it is 3.
524 return isSafe;
525}
526
527/// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified
528/// allocation, but only if cleaned up, perform the cleanups required.
529void SROA::CanonicalizeAllocaUsers(AllocationInst *AI) {
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000530 // At this point, we know that the end result will be SROA'd and promoted, so
531 // we can insert ugly code if required so long as sroa+mem2reg will clean it
532 // up.
533 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
534 UI != E; ) {
535 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(*UI++);
Reid Spencer93396382004-11-15 17:29:41 +0000536 gep_type_iterator I = gep_type_begin(GEPI);
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000537 ++I;
Chris Lattner88819122004-11-14 04:24:28 +0000538
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000539 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
540 uint64_t NumElements = AT->getNumElements();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000541
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000542 if (!isa<ConstantInt>(I.getOperand())) {
543 if (NumElements == 1) {
Reid Spencerc635f472006-12-31 05:48:39 +0000544 GEPI->setOperand(2, Constant::getNullValue(Type::Int32Ty));
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000545 } else {
546 assert(NumElements == 2 && "Unhandled case!");
547 // All users of the GEP must be loads. At each use of the GEP, insert
548 // two loads of the appropriate indexed GEP and select between them.
Reid Spencer266e42b2006-12-23 06:05:41 +0000549 Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(),
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000550 Constant::getNullValue(I.getOperand()->getType()),
Reid Spencer266e42b2006-12-23 06:05:41 +0000551 "isone", GEPI);
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000552 // Insert the new GEP instructions, which are properly indexed.
Chris Lattnera7315132007-02-12 22:56:41 +0000553 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
Reid Spencerc635f472006-12-31 05:48:39 +0000554 Indices[1] = Constant::getNullValue(Type::Int32Ty);
Chris Lattnera7315132007-02-12 22:56:41 +0000555 Value *ZeroIdx = new GetElementPtrInst(GEPI->getOperand(0),
556 &Indices[0], Indices.size(),
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000557 GEPI->getName()+".0", GEPI);
Reid Spencerc635f472006-12-31 05:48:39 +0000558 Indices[1] = ConstantInt::get(Type::Int32Ty, 1);
Chris Lattnera7315132007-02-12 22:56:41 +0000559 Value *OneIdx = new GetElementPtrInst(GEPI->getOperand(0),
560 &Indices[0], Indices.size(),
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000561 GEPI->getName()+".1", GEPI);
562 // Replace all loads of the variable index GEP with loads from both
563 // indexes and a select.
564 while (!GEPI->use_empty()) {
565 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
566 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
567 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
568 Value *R = new SelectInst(IsOne, One, Zero, LI->getName(), LI);
569 LI->replaceAllUsesWith(R);
570 LI->eraseFromParent();
571 }
572 GEPI->eraseFromParent();
573 }
574 }
575 }
576 }
Chris Lattner6e5398d2003-05-30 04:15:41 +0000577}
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000578
579/// MergeInType - Add the 'In' type to the accumulated type so far. If the
580/// types are incompatible, return true, otherwise update Accum and return
581/// false.
Chris Lattner3323ce12006-04-14 21:42:41 +0000582///
Chris Lattner8f7b7752006-12-15 07:32:38 +0000583/// There are three cases we handle here:
584/// 1) An effectively-integer union, where the pieces are stored into as
Chris Lattner3323ce12006-04-14 21:42:41 +0000585/// smaller integers (common with byte swap and other idioms).
Chris Lattner8f7b7752006-12-15 07:32:38 +0000586/// 2) A union of vector types of the same size and potentially its elements.
587/// Here we turn element accesses into insert/extract element operations.
588/// 3) A union of scalar types, such as int/float or int/pointer. Here we
589/// merge together into integers, allowing the xform to work with #1 as
590/// well.
Chris Lattner05f82722006-10-08 23:28:04 +0000591static bool MergeInType(const Type *In, const Type *&Accum,
592 const TargetData &TD) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000593 // If this is our first type, just use it.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000594 const VectorType *PTy;
Chris Lattner3323ce12006-04-14 21:42:41 +0000595 if (Accum == Type::VoidTy || In == Accum) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000596 Accum = In;
Chris Lattner8f7b7752006-12-15 07:32:38 +0000597 } else if (In == Type::VoidTy) {
598 // Noop.
Chris Lattner03c49532007-01-15 02:27:26 +0000599 } else if (In->isInteger() && Accum->isInteger()) { // integer union.
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000600 // Otherwise pick whichever type is larger.
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000601 if (cast<IntegerType>(In)->getBitWidth() >
602 cast<IntegerType>(Accum)->getBitWidth())
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000603 Accum = In;
Chris Lattner05f82722006-10-08 23:28:04 +0000604 } else if (isa<PointerType>(In) && isa<PointerType>(Accum)) {
Chris Lattner41b44222006-10-08 23:53:04 +0000605 // Pointer unions just stay as one of the pointers.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000606 } else if (isa<VectorType>(In) || isa<VectorType>(Accum)) {
607 if ((PTy = dyn_cast<VectorType>(Accum)) &&
Chris Lattner8f7b7752006-12-15 07:32:38 +0000608 PTy->getElementType() == In) {
609 // Accum is a vector, and we are accessing an element: ok.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000610 } else if ((PTy = dyn_cast<VectorType>(In)) &&
Chris Lattner8f7b7752006-12-15 07:32:38 +0000611 PTy->getElementType() == Accum) {
612 // In is a vector, and accum is an element: ok, remember In.
613 Accum = In;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000614 } else if ((PTy = dyn_cast<VectorType>(In)) && isa<VectorType>(Accum) &&
615 PTy->getBitWidth() == cast<VectorType>(Accum)->getBitWidth()) {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000616 // Two vectors of the same size: keep Accum.
617 } else {
618 // Cannot insert an short into a <4 x int> or handle
619 // <2 x int> -> <4 x int>
620 return true;
621 }
Chris Lattner7c1dff92006-12-13 02:26:45 +0000622 } else {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000623 // Pointer/FP/Integer unions merge together as integers.
624 switch (Accum->getTypeID()) {
625 case Type::PointerTyID: Accum = TD.getIntPtrType(); break;
Reid Spencerc635f472006-12-31 05:48:39 +0000626 case Type::FloatTyID: Accum = Type::Int32Ty; break;
627 case Type::DoubleTyID: Accum = Type::Int64Ty; break;
Chris Lattner8f7b7752006-12-15 07:32:38 +0000628 default:
Chris Lattner03c49532007-01-15 02:27:26 +0000629 assert(Accum->isInteger() && "Unknown FP type!");
Chris Lattner8f7b7752006-12-15 07:32:38 +0000630 break;
631 }
632
633 switch (In->getTypeID()) {
634 case Type::PointerTyID: In = TD.getIntPtrType(); break;
Reid Spencerc635f472006-12-31 05:48:39 +0000635 case Type::FloatTyID: In = Type::Int32Ty; break;
636 case Type::DoubleTyID: In = Type::Int64Ty; break;
Chris Lattner8f7b7752006-12-15 07:32:38 +0000637 default:
Chris Lattner03c49532007-01-15 02:27:26 +0000638 assert(In->isInteger() && "Unknown FP type!");
Chris Lattner8f7b7752006-12-15 07:32:38 +0000639 break;
640 }
641 return MergeInType(In, Accum, TD);
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000642 }
643 return false;
644}
645
646/// getUIntAtLeastAsBitAs - Return an unsigned integer type that is at least
647/// as big as the specified type. If there is no suitable type, this returns
648/// null.
649const Type *getUIntAtLeastAsBitAs(unsigned NumBits) {
650 if (NumBits > 64) return 0;
Reid Spencerc635f472006-12-31 05:48:39 +0000651 if (NumBits > 32) return Type::Int64Ty;
652 if (NumBits > 16) return Type::Int32Ty;
653 if (NumBits > 8) return Type::Int16Ty;
654 return Type::Int8Ty;
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000655}
656
657/// CanConvertToScalar - V is a pointer. If we can convert the pointee to a
658/// single scalar integer type, return that type. Further, if the use is not
659/// a completely trivial use that mem2reg could promote, set IsNotTrivial. If
660/// there are no uses of this pointer, return Type::VoidTy to differentiate from
661/// failure.
662///
663const Type *SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial) {
664 const Type *UsedType = Type::VoidTy; // No uses, no forced type.
665 const TargetData &TD = getAnalysis<TargetData>();
666 const PointerType *PTy = cast<PointerType>(V->getType());
667
668 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
669 Instruction *User = cast<Instruction>(*UI);
670
671 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner05f82722006-10-08 23:28:04 +0000672 if (MergeInType(LI->getType(), UsedType, TD))
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000673 return 0;
674
675 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Reid Spencer2eadb532007-01-21 00:29:26 +0000676 // Storing the pointer, not into the value?
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000677 if (SI->getOperand(0) == V) return 0;
678
Chris Lattner3323ce12006-04-14 21:42:41 +0000679 // NOTE: We could handle storing of FP imms into integers here!
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000680
Chris Lattner05f82722006-10-08 23:28:04 +0000681 if (MergeInType(SI->getOperand(0)->getType(), UsedType, TD))
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000682 return 0;
Chris Lattner8f7b7752006-12-15 07:32:38 +0000683 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000684 IsNotTrivial = true;
685 const Type *SubTy = CanConvertToScalar(CI, IsNotTrivial);
Chris Lattner05f82722006-10-08 23:28:04 +0000686 if (!SubTy || MergeInType(SubTy, UsedType, TD)) return 0;
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000687 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
688 // Check to see if this is stepping over an element: GEP Ptr, int C
689 if (GEP->getNumOperands() == 2 && isa<ConstantInt>(GEP->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000690 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000691 unsigned ElSize = TD.getTypeSize(PTy->getElementType());
692 unsigned BitOffset = Idx*ElSize*8;
693 if (BitOffset > 64 || !isPowerOf2_32(ElSize)) return 0;
694
695 IsNotTrivial = true;
696 const Type *SubElt = CanConvertToScalar(GEP, IsNotTrivial);
697 if (SubElt == 0) return 0;
Chris Lattner03c49532007-01-15 02:27:26 +0000698 if (SubElt != Type::VoidTy && SubElt->isInteger()) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000699 const Type *NewTy =
Chris Lattner41b44222006-10-08 23:53:04 +0000700 getUIntAtLeastAsBitAs(TD.getTypeSize(SubElt)*8+BitOffset);
Chris Lattner05f82722006-10-08 23:28:04 +0000701 if (NewTy == 0 || MergeInType(NewTy, UsedType, TD)) return 0;
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000702 continue;
703 }
704 } else if (GEP->getNumOperands() == 3 &&
705 isa<ConstantInt>(GEP->getOperand(1)) &&
706 isa<ConstantInt>(GEP->getOperand(2)) &&
707 cast<Constant>(GEP->getOperand(1))->isNullValue()) {
708 // We are stepping into an element, e.g. a structure or an array:
709 // GEP Ptr, int 0, uint C
710 const Type *AggTy = PTy->getElementType();
Reid Spencere0fc4df2006-10-20 07:07:24 +0000711 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000712
713 if (const ArrayType *ATy = dyn_cast<ArrayType>(AggTy)) {
714 if (Idx >= ATy->getNumElements()) return 0; // Out of range.
Reid Spencer09575ba2007-02-15 03:39:18 +0000715 } else if (const VectorType *VectorTy = dyn_cast<VectorType>(AggTy)) {
Chris Lattner3323ce12006-04-14 21:42:41 +0000716 // Getting an element of the packed vector.
Reid Spencer09575ba2007-02-15 03:39:18 +0000717 if (Idx >= VectorTy->getNumElements()) return 0; // Out of range.
Chris Lattner3323ce12006-04-14 21:42:41 +0000718
Reid Spencer09575ba2007-02-15 03:39:18 +0000719 // Merge in the vector type.
720 if (MergeInType(VectorTy, UsedType, TD)) return 0;
Chris Lattner3323ce12006-04-14 21:42:41 +0000721
722 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
723 if (SubTy == 0) return 0;
724
Chris Lattner05f82722006-10-08 23:28:04 +0000725 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
Chris Lattner3323ce12006-04-14 21:42:41 +0000726 return 0;
727
728 // We'll need to change this to an insert/extract element operation.
729 IsNotTrivial = true;
730 continue; // Everything looks ok
731
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000732 } else if (isa<StructType>(AggTy)) {
733 // Structs are always ok.
734 } else {
735 return 0;
736 }
737 const Type *NTy = getUIntAtLeastAsBitAs(TD.getTypeSize(AggTy)*8);
Chris Lattner05f82722006-10-08 23:28:04 +0000738 if (NTy == 0 || MergeInType(NTy, UsedType, TD)) return 0;
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000739 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
740 if (SubTy == 0) return 0;
Chris Lattner05f82722006-10-08 23:28:04 +0000741 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000742 return 0;
743 continue; // Everything looks ok
744 }
745 return 0;
746 } else {
747 // Cannot handle this!
748 return 0;
749 }
750 }
751
752 return UsedType;
753}
754
755/// ConvertToScalar - The specified alloca passes the CanConvertToScalar
756/// predicate and is non-trivial. Convert it to something that can be trivially
757/// promoted into a register by mem2reg.
758void SROA::ConvertToScalar(AllocationInst *AI, const Type *ActualTy) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000759 DOUT << "CONVERT TO SCALAR: " << *AI << " TYPE = "
760 << *ActualTy << "\n";
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000761 ++NumConverted;
762
763 BasicBlock *EntryBlock = AI->getParent();
764 assert(EntryBlock == &EntryBlock->getParent()->front() &&
765 "Not in the entry block!");
766 EntryBlock->getInstList().remove(AI); // Take the alloca out of the program.
767
768 // Create and insert the alloca.
Chris Lattner3323ce12006-04-14 21:42:41 +0000769 AllocaInst *NewAI = new AllocaInst(ActualTy, 0, AI->getName(),
770 EntryBlock->begin());
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000771 ConvertUsesToScalar(AI, NewAI, 0);
772 delete AI;
773}
774
775
776/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
Chris Lattner3323ce12006-04-14 21:42:41 +0000777/// directly. This happens when we are converting an "integer union" to a
778/// single integer scalar, or when we are converting a "vector union" to a
779/// vector with insert/extractelement instructions.
780///
781/// Offset is an offset from the original alloca, in bits that need to be
782/// shifted to the right. By the end of this, there should be no uses of Ptr.
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000783void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000784 bool isVectorInsert = isa<VectorType>(NewAI->getType()->getElementType());
Chris Lattner41b44222006-10-08 23:53:04 +0000785 const TargetData &TD = getAnalysis<TargetData>();
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000786 while (!Ptr->use_empty()) {
787 Instruction *User = cast<Instruction>(Ptr->use_back());
788
789 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
790 // The load is a bit extract from NewAI shifted right by Offset bits.
791 Value *NV = new LoadInst(NewAI, LI->getName(), LI);
Chris Lattner3323ce12006-04-14 21:42:41 +0000792 if (NV->getType() != LI->getType()) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000793 if (const VectorType *PTy = dyn_cast<VectorType>(NV->getType())) {
Reid Spencer09575ba2007-02-15 03:39:18 +0000794 // If the result alloca is a vector type, this is either an element
795 // access or a bitcast to another vector type.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000796 if (isa<VectorType>(LI->getType())) {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000797 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
Chris Lattner216c3022006-12-10 23:56:50 +0000798 } else {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000799 // Must be an element access.
800 unsigned Elt = Offset/(TD.getTypeSize(PTy->getElementType())*8);
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000801 NV = new ExtractElementInst(
802 NV, ConstantInt::get(Type::Int32Ty, Elt), "tmp", LI);
Chris Lattner216c3022006-12-10 23:56:50 +0000803 }
Chris Lattner8f7b7752006-12-15 07:32:38 +0000804 } else if (isa<PointerType>(NV->getType())) {
805 assert(isa<PointerType>(LI->getType()));
806 // Must be ptr->ptr cast. Anything else would result in NV being
807 // an integer.
808 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
809 } else {
Chris Lattner03c49532007-01-15 02:27:26 +0000810 assert(NV->getType()->isInteger() && "Unknown promotion!");
Chris Lattner8f7b7752006-12-15 07:32:38 +0000811 if (Offset && Offset < TD.getTypeSize(NV->getType())*8) {
Reid Spencer0d5f9232007-02-02 14:08:20 +0000812 NV = BinaryOperator::createLShr(NV,
Reid Spencer2341c222007-02-02 02:16:23 +0000813 ConstantInt::get(NV->getType(), Offset),
814 LI->getName(), LI);
Chris Lattner8f7b7752006-12-15 07:32:38 +0000815 }
816
817 // If the result is an integer, this is a trunc or bitcast.
Chris Lattner03c49532007-01-15 02:27:26 +0000818 if (LI->getType()->isInteger()) {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000819 NV = CastInst::createTruncOrBitCast(NV, LI->getType(),
820 LI->getName(), LI);
821 } else if (LI->getType()->isFloatingPoint()) {
822 // If needed, truncate the integer to the appropriate size.
Reid Spencer8f166b02007-01-08 16:32:00 +0000823 if (NV->getType()->getPrimitiveSizeInBits() >
824 LI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000825 switch (LI->getType()->getTypeID()) {
826 default: assert(0 && "Unknown FP type!");
827 case Type::FloatTyID:
Reid Spencerc635f472006-12-31 05:48:39 +0000828 NV = new TruncInst(NV, Type::Int32Ty, LI->getName(), LI);
Chris Lattner8f7b7752006-12-15 07:32:38 +0000829 break;
830 case Type::DoubleTyID:
Reid Spencerc635f472006-12-31 05:48:39 +0000831 NV = new TruncInst(NV, Type::Int64Ty, LI->getName(), LI);
Chris Lattner8f7b7752006-12-15 07:32:38 +0000832 break;
833 }
834 }
835
836 // Then do a bitcast.
837 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
838 } else {
839 // Otherwise must be a pointer.
840 NV = new IntToPtrInst(NV, LI->getType(), LI->getName(), LI);
841 }
Chris Lattner3323ce12006-04-14 21:42:41 +0000842 }
843 }
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000844 LI->replaceAllUsesWith(NV);
845 LI->eraseFromParent();
846 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
847 assert(SI->getOperand(0) != Ptr && "Consistency error!");
848
849 // Convert the stored type to the actual type, shift it left to insert
850 // then 'or' into place.
851 Value *SV = SI->getOperand(0);
Chris Lattner3323ce12006-04-14 21:42:41 +0000852 const Type *AllocaType = NewAI->getType()->getElementType();
853 if (SV->getType() != AllocaType) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000854 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
Chris Lattner3323ce12006-04-14 21:42:41 +0000855
Reid Spencerd84d35b2007-02-15 02:26:10 +0000856 if (const VectorType *PTy = dyn_cast<VectorType>(AllocaType)) {
Reid Spencer09575ba2007-02-15 03:39:18 +0000857 // If the result alloca is a vector type, this is either an element
858 // access or a bitcast to another vector type.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000859 if (isa<VectorType>(SV->getType())) {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000860 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
861 } else {
862 // Must be an element insertion.
863 unsigned Elt = Offset/(TD.getTypeSize(PTy->getElementType())*8);
864 SV = new InsertElementInst(Old, SV,
Reid Spencerc635f472006-12-31 05:48:39 +0000865 ConstantInt::get(Type::Int32Ty, Elt),
Chris Lattner8f7b7752006-12-15 07:32:38 +0000866 "tmp", SI);
867 }
Chris Lattner3323ce12006-04-14 21:42:41 +0000868 } else {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000869 // If SV is a float, convert it to the appropriate integer type.
870 // If it is a pointer, do the same, and also handle ptr->ptr casts
871 // here.
872 switch (SV->getType()->getTypeID()) {
873 default:
874 assert(!SV->getType()->isFloatingPoint() && "Unknown FP type!");
875 break;
876 case Type::FloatTyID:
Reid Spencerc635f472006-12-31 05:48:39 +0000877 SV = new BitCastInst(SV, Type::Int32Ty, SV->getName(), SI);
Chris Lattner8f7b7752006-12-15 07:32:38 +0000878 break;
879 case Type::DoubleTyID:
Reid Spencerc635f472006-12-31 05:48:39 +0000880 SV = new BitCastInst(SV, Type::Int64Ty, SV->getName(), SI);
Chris Lattner8f7b7752006-12-15 07:32:38 +0000881 break;
882 case Type::PointerTyID:
883 if (isa<PointerType>(AllocaType))
884 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
885 else
886 SV = new PtrToIntInst(SV, TD.getIntPtrType(), SV->getName(), SI);
887 break;
888 }
889
890 unsigned SrcSize = TD.getTypeSize(SV->getType())*8;
891
892 // Always zero extend the value if needed.
893 if (SV->getType() != AllocaType)
894 SV = CastInst::createZExtOrBitCast(SV, AllocaType,
895 SV->getName(), SI);
896 if (Offset && Offset < AllocaType->getPrimitiveSizeInBits())
Reid Spencer0d5f9232007-02-02 14:08:20 +0000897 SV = BinaryOperator::createShl(SV,
Reid Spencer2341c222007-02-02 02:16:23 +0000898 ConstantInt::get(SV->getType(), Offset),
899 SV->getName()+".adj", SI);
Chris Lattner3323ce12006-04-14 21:42:41 +0000900 // Mask out the bits we are about to insert from the old value.
Chris Lattner41b44222006-10-08 23:53:04 +0000901 unsigned TotalBits = TD.getTypeSize(SV->getType())*8;
Chris Lattner8f7b7752006-12-15 07:32:38 +0000902 if (TotalBits != SrcSize) {
903 assert(TotalBits > SrcSize);
904 uint64_t Mask = ~(((1ULL << SrcSize)-1) << Offset);
Reid Spencera94d3942007-01-19 21:13:56 +0000905 Mask = Mask & cast<IntegerType>(SV->getType())->getBitMask();
Chris Lattner3323ce12006-04-14 21:42:41 +0000906 Old = BinaryOperator::createAnd(Old,
Reid Spencere0fc4df2006-10-20 07:07:24 +0000907 ConstantInt::get(Old->getType(), Mask),
Chris Lattner3323ce12006-04-14 21:42:41 +0000908 Old->getName()+".mask", SI);
909 SV = BinaryOperator::createOr(Old, SV, SV->getName()+".ins", SI);
910 }
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000911 }
912 }
913 new StoreInst(SV, NewAI, SI);
914 SI->eraseFromParent();
915
916 } else if (CastInst *CI = dyn_cast<CastInst>(User)) {
917 unsigned NewOff = Offset;
918 const TargetData &TD = getAnalysis<TargetData>();
Chris Lattner3323ce12006-04-14 21:42:41 +0000919 if (TD.isBigEndian() && !isVectorInsert) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000920 // Adjust the pointer. For example, storing 16-bits into a 32-bit
921 // alloca with just a cast makes it modify the top 16-bits.
922 const Type *SrcTy = cast<PointerType>(Ptr->getType())->getElementType();
923 const Type *DstTy = cast<PointerType>(CI->getType())->getElementType();
924 int PtrDiffBits = TD.getTypeSize(SrcTy)*8-TD.getTypeSize(DstTy)*8;
925 NewOff += PtrDiffBits;
926 }
927 ConvertUsesToScalar(CI, NewAI, NewOff);
928 CI->eraseFromParent();
929 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
930 const PointerType *AggPtrTy =
931 cast<PointerType>(GEP->getOperand(0)->getType());
932 const TargetData &TD = getAnalysis<TargetData>();
933 unsigned AggSizeInBits = TD.getTypeSize(AggPtrTy->getElementType())*8;
934
935 // Check to see if this is stepping over an element: GEP Ptr, int C
936 unsigned NewOffset = Offset;
937 if (GEP->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000938 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000939 unsigned BitOffset = Idx*AggSizeInBits;
940
Chris Lattner3323ce12006-04-14 21:42:41 +0000941 if (TD.isLittleEndian() || isVectorInsert)
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000942 NewOffset += BitOffset;
943 else
944 NewOffset -= BitOffset;
945
946 } else if (GEP->getNumOperands() == 3) {
947 // We know that operand #2 is zero.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000948 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000949 const Type *AggTy = AggPtrTy->getElementType();
950 if (const SequentialType *SeqTy = dyn_cast<SequentialType>(AggTy)) {
951 unsigned ElSizeBits = TD.getTypeSize(SeqTy->getElementType())*8;
952
Chris Lattner3323ce12006-04-14 21:42:41 +0000953 if (TD.isLittleEndian() || isVectorInsert)
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000954 NewOffset += ElSizeBits*Idx;
955 else
956 NewOffset += AggSizeInBits-ElSizeBits*(Idx+1);
957 } else if (const StructType *STy = dyn_cast<StructType>(AggTy)) {
Chris Lattnerc473d8e2007-02-10 19:55:17 +0000958 unsigned EltBitOffset =
959 TD.getStructLayout(STy)->getElementOffset(Idx)*8;
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000960
Chris Lattner3323ce12006-04-14 21:42:41 +0000961 if (TD.isLittleEndian() || isVectorInsert)
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000962 NewOffset += EltBitOffset;
963 else {
964 const PointerType *ElPtrTy = cast<PointerType>(GEP->getType());
965 unsigned ElSizeBits = TD.getTypeSize(ElPtrTy->getElementType())*8;
966 NewOffset += AggSizeInBits-(EltBitOffset+ElSizeBits);
967 }
968
969 } else {
970 assert(0 && "Unsupported operation!");
971 abort();
972 }
973 } else {
974 assert(0 && "Unsupported operation!");
975 abort();
976 }
977 ConvertUsesToScalar(GEP, NewAI, NewOffset);
978 GEP->eraseFromParent();
979 } else {
980 assert(0 && "Unsupported operation!");
981 abort();
982 }
983 }
984}