blob: 480f2aae2ff3f21ab3c43dc26496c5b8a6274355 [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"
27#include "llvm/Pass.h"
Misha Brukman2b3387a2004-07-29 17:05:13 +000028#include "llvm/Instructions.h"
Chris Lattner5d8a12e2003-09-11 16:45:55 +000029#include "llvm/Analysis/Dominators.h"
30#include "llvm/Target/TargetData.h"
31#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Chris Lattner996795b2006-06-28 23:17:24 +000032#include "llvm/Support/Debug.h"
Chris Lattner3b0a62d2005-12-12 07:19:13 +000033#include "llvm/Support/GetElementPtrTypeIterator.h"
34#include "llvm/Support/MathExtras.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000035#include "llvm/Support/Compiler.h"
Chris Lattnera7315132007-02-12 22:56:41 +000036#include "llvm/ADT/SmallVector.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000037#include "llvm/ADT/Statistic.h"
38#include "llvm/ADT/StringExtras.h"
Chris Lattner40d2aeb2003-12-02 17:43:55 +000039using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000040
Chris Lattner79a42ac2006-12-19 21:40:18 +000041STATISTIC(NumReplaced, "Number of allocas broken up");
42STATISTIC(NumPromoted, "Number of allocas promoted");
43STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattnerfb41a502003-05-27 15:45:27 +000044
Chris Lattner79a42ac2006-12-19 21:40:18 +000045namespace {
Chris Lattner996795b2006-06-28 23:17:24 +000046 struct VISIBILITY_HIDDEN SROA : public FunctionPass {
Chris Lattnerfb41a502003-05-27 15:45:27 +000047 bool runOnFunction(Function &F);
48
Chris Lattner5d8a12e2003-09-11 16:45:55 +000049 bool performScalarRepl(Function &F);
50 bool performPromotion(Function &F);
51
Chris Lattnerc8174582003-08-31 00:45:13 +000052 // getAnalysisUsage - This pass does not require any passes, but we know it
53 // will not alter the CFG, so say so.
54 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnera906bac2003-10-05 21:20:13 +000055 AU.addRequired<DominatorTree>();
Chris Lattner5d8a12e2003-09-11 16:45:55 +000056 AU.addRequired<DominanceFrontier>();
57 AU.addRequired<TargetData>();
Chris Lattnerc8174582003-08-31 00:45:13 +000058 AU.setPreservesCFG();
59 }
60
Chris Lattnerfb41a502003-05-27 15:45:27 +000061 private:
Chris Lattner88819122004-11-14 04:24:28 +000062 int isSafeElementUse(Value *Ptr);
63 int isSafeUseOfAllocation(Instruction *User);
64 int isSafeAllocaToScalarRepl(AllocationInst *AI);
65 void CanonicalizeAllocaUsers(AllocationInst *AI);
Chris Lattnerfb41a502003-05-27 15:45:27 +000066 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
Chris Lattner3b0a62d2005-12-12 07:19:13 +000067
68 const Type *CanConvertToScalar(Value *V, bool &IsNotTrivial);
69 void ConvertToScalar(AllocationInst *AI, const Type *Ty);
70 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset);
Chris Lattnerfb41a502003-05-27 15:45:27 +000071 };
72
Chris Lattnerc2d3d312006-08-27 22:42:52 +000073 RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
Chris Lattnerfb41a502003-05-27 15:45:27 +000074}
75
Brian Gaeke960707c2003-11-11 22:41:34 +000076// Public interface to the ScalarReplAggregates pass
Chris Lattner3e860842004-09-20 04:43:15 +000077FunctionPass *llvm::createScalarReplAggregatesPass() { return new SROA(); }
Chris Lattnerfb41a502003-05-27 15:45:27 +000078
79
Chris Lattnerfb41a502003-05-27 15:45:27 +000080bool SROA::runOnFunction(Function &F) {
Chris Lattner9a95f2a2003-09-12 15:36:03 +000081 bool Changed = performPromotion(F);
82 while (1) {
83 bool LocalChange = performScalarRepl(F);
84 if (!LocalChange) break; // No need to repromote if no scalarrepl
85 Changed = true;
86 LocalChange = performPromotion(F);
87 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
88 }
Chris Lattner5d8a12e2003-09-11 16:45:55 +000089
90 return Changed;
91}
92
93
94bool SROA::performPromotion(Function &F) {
95 std::vector<AllocaInst*> Allocas;
96 const TargetData &TD = getAnalysis<TargetData>();
Chris Lattnera906bac2003-10-05 21:20:13 +000097 DominatorTree &DT = getAnalysis<DominatorTree>();
98 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
Chris Lattner5d8a12e2003-09-11 16:45:55 +000099
Chris Lattner5dac64f2003-09-20 14:39:18 +0000100 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000101
Chris Lattner9a95f2a2003-09-12 15:36:03 +0000102 bool Changed = false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000103
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000104 while (1) {
105 Allocas.clear();
106
107 // Find allocas that are safe to promote, by looking at all instructions in
108 // the entry node
109 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
110 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
111 if (isAllocaPromotable(AI, TD))
112 Allocas.push_back(AI);
113
114 if (Allocas.empty()) break;
115
Chris Lattnera906bac2003-10-05 21:20:13 +0000116 PromoteMemToReg(Allocas, DT, DF, TD);
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000117 NumPromoted += Allocas.size();
118 Changed = true;
119 }
120
121 return Changed;
122}
123
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000124// performScalarRepl - This algorithm is a simple worklist driven algorithm,
125// which runs on all of the malloc/alloca instructions in the function, removing
126// them if they are only used by getelementptr instructions.
127//
128bool SROA::performScalarRepl(Function &F) {
Chris Lattnerfb41a502003-05-27 15:45:27 +0000129 std::vector<AllocationInst*> WorkList;
130
131 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
Chris Lattner5dac64f2003-09-20 14:39:18 +0000132 BasicBlock &BB = F.getEntryBlock();
Chris Lattnerfb41a502003-05-27 15:45:27 +0000133 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
134 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
135 WorkList.push_back(A);
136
137 // Process the worklist
138 bool Changed = false;
139 while (!WorkList.empty()) {
140 AllocationInst *AI = WorkList.back();
141 WorkList.pop_back();
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000142
Chris Lattnerf171af92006-12-22 23:14:42 +0000143 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
144 // with unused elements.
145 if (AI->use_empty()) {
146 AI->eraseFromParent();
147 continue;
148 }
149
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000150 // If we can turn this aggregate value (potentially with casts) into a
151 // simple scalar value that can be mem2reg'd into a register value.
152 bool IsNotTrivial = false;
153 if (const Type *ActualType = CanConvertToScalar(AI, IsNotTrivial))
Chris Lattnerdae49df2006-04-20 20:48:50 +0000154 if (IsNotTrivial && ActualType != Type::VoidTy) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000155 ConvertToScalar(AI, ActualType);
156 Changed = true;
157 continue;
158 }
Chris Lattnerfb41a502003-05-27 15:45:27 +0000159
160 // We cannot transform the allocation instruction if it is an array
Chris Lattnerc16b2102003-05-27 16:09:27 +0000161 // allocation (allocations OF arrays are ok though), and an allocation of a
162 // scalar value cannot be decomposed at all.
163 //
Chris Lattnerfb41a502003-05-27 15:45:27 +0000164 if (AI->isArrayAllocation() ||
Chris Lattnerc16b2102003-05-27 16:09:27 +0000165 (!isa<StructType>(AI->getAllocatedType()) &&
166 !isa<ArrayType>(AI->getAllocatedType()))) continue;
167
Chris Lattner6e5398d2003-05-30 04:15:41 +0000168 // Check that all of the users of the allocation are capable of being
169 // transformed.
Chris Lattner88819122004-11-14 04:24:28 +0000170 switch (isSafeAllocaToScalarRepl(AI)) {
171 default: assert(0 && "Unexpected value!");
172 case 0: // Not safe to scalar replace.
Chris Lattner6e5398d2003-05-30 04:15:41 +0000173 continue;
Chris Lattner88819122004-11-14 04:24:28 +0000174 case 1: // Safe, but requires cleanup/canonicalizations first
175 CanonicalizeAllocaUsers(AI);
176 case 3: // Safe to scalar replace.
177 break;
178 }
Chris Lattnerfb41a502003-05-27 15:45:27 +0000179
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000180 DOUT << "Found inst to xform: " << *AI;
Chris Lattnerfb41a502003-05-27 15:45:27 +0000181 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000182
Chris Lattnerfb41a502003-05-27 15:45:27 +0000183 std::vector<AllocaInst*> ElementAllocas;
184 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
185 ElementAllocas.reserve(ST->getNumContainedTypes());
186 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Nate Begeman848622f2005-11-05 09:21:28 +0000187 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
188 AI->getAlignment(),
Chris Lattnerfb41a502003-05-27 15:45:27 +0000189 AI->getName() + "." + utostr(i), AI);
190 ElementAllocas.push_back(NA);
191 WorkList.push_back(NA); // Add to worklist for recursive processing
192 }
193 } else {
Chris Lattner6e5398d2003-05-30 04:15:41 +0000194 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
Chris Lattnerfb41a502003-05-27 15:45:27 +0000195 ElementAllocas.reserve(AT->getNumElements());
196 const Type *ElTy = AT->getElementType();
197 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Nate Begeman848622f2005-11-05 09:21:28 +0000198 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Chris Lattnerfb41a502003-05-27 15:45:27 +0000199 AI->getName() + "." + utostr(i), AI);
200 ElementAllocas.push_back(NA);
201 WorkList.push_back(NA); // Add to worklist for recursive processing
202 }
203 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000204
Chris Lattnerfb41a502003-05-27 15:45:27 +0000205 // Now that we have created the alloca instructions that we want to use,
206 // expand the getelementptr instructions to use them.
207 //
Chris Lattnerb5f8eb82004-06-19 02:02:22 +0000208 while (!AI->use_empty()) {
209 Instruction *User = cast<Instruction>(AI->use_back());
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000210 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
211 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
Misha Brukmanb1c93172005-04-21 23:48:37 +0000212 unsigned Idx =
Reid Spencere0fc4df2006-10-20 07:07:24 +0000213 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000214
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000215 assert(Idx < ElementAllocas.size() && "Index out of range?");
216 AllocaInst *AllocaToUse = ElementAllocas[Idx];
Misha Brukmanb1c93172005-04-21 23:48:37 +0000217
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000218 Value *RepValue;
219 if (GEPI->getNumOperands() == 3) {
220 // Do not insert a new getelementptr instruction with zero indices, only
221 // to have it optimized out later.
222 RepValue = AllocaToUse;
Chris Lattnerfb41a502003-05-27 15:45:27 +0000223 } else {
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000224 // We are indexing deeply into the structure, so we still need a
225 // getelement ptr instruction to finish the indexing. This may be
226 // expanded itself once the worklist is rerun.
227 //
Chris Lattnera7315132007-02-12 22:56:41 +0000228 SmallVector<Value*, 8> NewArgs;
Reid Spencerc635f472006-12-31 05:48:39 +0000229 NewArgs.push_back(Constant::getNullValue(Type::Int32Ty));
Chris Lattnera7315132007-02-12 22:56:41 +0000230 NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
231 RepValue = new GetElementPtrInst(AllocaToUse, &NewArgs[0],
232 NewArgs.size(), "", GEPI);
Chris Lattner6e0123b2007-02-11 01:23:03 +0000233 RepValue->takeName(GEPI);
Chris Lattnerfb41a502003-05-27 15:45:27 +0000234 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000235
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000236 // Move all of the users over to the new GEP.
237 GEPI->replaceAllUsesWith(RepValue);
238 // Delete the old GEP
239 GEPI->eraseFromParent();
Chris Lattnerfb41a502003-05-27 15:45:27 +0000240 }
241
242 // Finally, delete the Alloca instruction
Chris Lattnerf171af92006-12-22 23:14:42 +0000243 AI->eraseFromParent();
Chris Lattnerc16b2102003-05-27 16:09:27 +0000244 NumReplaced++;
Chris Lattnerfb41a502003-05-27 15:45:27 +0000245 }
246
247 return Changed;
248}
Chris Lattner6e5398d2003-05-30 04:15:41 +0000249
250
Chris Lattner88819122004-11-14 04:24:28 +0000251/// isSafeElementUse - Check to see if this use is an allowed use for a
252/// getelementptr instruction of an array aggregate allocation.
253///
254int SROA::isSafeElementUse(Value *Ptr) {
255 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
256 I != E; ++I) {
257 Instruction *User = cast<Instruction>(*I);
258 switch (User->getOpcode()) {
259 case Instruction::Load: break;
260 case Instruction::Store:
261 // Store is ok if storing INTO the pointer, not storing the pointer
262 if (User->getOperand(0) == Ptr) return 0;
263 break;
264 case Instruction::GetElementPtr: {
265 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
266 if (GEP->getNumOperands() > 1) {
267 if (!isa<Constant>(GEP->getOperand(1)) ||
268 !cast<Constant>(GEP->getOperand(1))->isNullValue())
269 return 0; // Using pointer arithmetic to navigate the array...
270 }
271 if (!isSafeElementUse(GEP)) return 0;
272 break;
273 }
274 default:
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000275 DOUT << " Transformation preventing inst: " << *User;
Chris Lattner88819122004-11-14 04:24:28 +0000276 return 0;
277 }
278 }
279 return 3; // All users look ok :)
280}
281
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000282/// AllUsersAreLoads - Return true if all users of this value are loads.
283static bool AllUsersAreLoads(Value *Ptr) {
284 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
285 I != E; ++I)
286 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
287 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000288 return true;
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000289}
290
Chris Lattner6e5398d2003-05-30 04:15:41 +0000291/// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
292/// aggregate allocation.
293///
Chris Lattner88819122004-11-14 04:24:28 +0000294int SROA::isSafeUseOfAllocation(Instruction *User) {
295 if (!isa<GetElementPtrInst>(User)) return 0;
Chris Lattner52310702003-11-25 21:09:18 +0000296
297 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
298 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
299
Chris Lattnerfc34f8b2006-03-08 01:05:29 +0000300 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
Chris Lattner52310702003-11-25 21:09:18 +0000301 if (I == E ||
302 I.getOperand() != Constant::getNullValue(I.getOperand()->getType()))
Chris Lattner88819122004-11-14 04:24:28 +0000303 return 0;
Chris Lattner52310702003-11-25 21:09:18 +0000304
305 ++I;
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000306 if (I == E) return 0; // ran out of GEP indices??
Chris Lattner52310702003-11-25 21:09:18 +0000307
308 // If this is a use of an array allocation, do a bit more checking for sanity.
309 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
310 uint64_t NumElements = AT->getNumElements();
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000311
Reid Spencerde46e482006-11-02 20:25:50 +0000312 if (isa<ConstantInt>(I.getOperand())) {
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000313 // Check to make sure that index falls within the array. If not,
314 // something funny is going on, so we won't do the optimization.
315 //
Reid Spencere0fc4df2006-10-20 07:07:24 +0000316 if (cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue() >= NumElements)
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000317 return 0;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000318
Chris Lattnerfc34f8b2006-03-08 01:05:29 +0000319 // We cannot scalar repl this level of the array unless any array
320 // sub-indices are in-range constants. In particular, consider:
321 // A[0][i]. We cannot know that the user isn't doing invalid things like
322 // allowing i to index an out-of-range subscript that accesses A[1].
323 //
324 // Scalar replacing *just* the outer index of the array is probably not
325 // going to be a win anyway, so just give up.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000326 for (++I; I != E && (isa<ArrayType>(*I) || isa<VectorType>(*I)); ++I) {
Chris Lattner4967f6d2006-11-07 22:42:47 +0000327 uint64_t NumElements;
328 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*I))
329 NumElements = SubArrayTy->getNumElements();
330 else
Reid Spencerd84d35b2007-02-15 02:26:10 +0000331 NumElements = cast<VectorType>(*I)->getNumElements();
Chris Lattner4967f6d2006-11-07 22:42:47 +0000332
Chris Lattnerfc34f8b2006-03-08 01:05:29 +0000333 if (!isa<ConstantInt>(I.getOperand())) return 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +0000334 if (cast<ConstantInt>(I.getOperand())->getZExtValue() >= NumElements)
Chris Lattnerfc34f8b2006-03-08 01:05:29 +0000335 return 0;
336 }
337
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000338 } else {
339 // If this is an array index and the index is not constant, we cannot
340 // promote... that is unless the array has exactly one or two elements in
341 // it, in which case we CAN promote it, but we have to canonicalize this
342 // out if this is the only problem.
Chris Lattnerfc34f8b2006-03-08 01:05:29 +0000343 if ((NumElements == 1 || NumElements == 2) &&
344 AllUsersAreLoads(GEPI))
345 return 1; // Canonicalization required!
Chris Lattner88819122004-11-14 04:24:28 +0000346 return 0;
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000347 }
Chris Lattner6e5398d2003-05-30 04:15:41 +0000348 }
Chris Lattner52310702003-11-25 21:09:18 +0000349
350 // If there are any non-simple uses of this getelementptr, make sure to reject
351 // them.
352 return isSafeElementUse(GEPI);
Chris Lattner6e5398d2003-05-30 04:15:41 +0000353}
354
Chris Lattner88819122004-11-14 04:24:28 +0000355/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
356/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
357/// or 1 if safe after canonicalization has been performed.
Chris Lattner6e5398d2003-05-30 04:15:41 +0000358///
Chris Lattner88819122004-11-14 04:24:28 +0000359int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
Chris Lattner6e5398d2003-05-30 04:15:41 +0000360 // Loop over the use list of the alloca. We can only transform it if all of
361 // the users are safe to transform.
362 //
Chris Lattner88819122004-11-14 04:24:28 +0000363 int isSafe = 3;
Chris Lattner6e5398d2003-05-30 04:15:41 +0000364 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
Chris Lattner88819122004-11-14 04:24:28 +0000365 I != E; ++I) {
366 isSafe &= isSafeUseOfAllocation(cast<Instruction>(*I));
367 if (isSafe == 0) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000368 DOUT << "Cannot transform: " << *AI << " due to user: " << **I;
Chris Lattner88819122004-11-14 04:24:28 +0000369 return 0;
Chris Lattner6e5398d2003-05-30 04:15:41 +0000370 }
Chris Lattner88819122004-11-14 04:24:28 +0000371 }
372 // If we require cleanup, isSafe is now 1, otherwise it is 3.
373 return isSafe;
374}
375
376/// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified
377/// allocation, but only if cleaned up, perform the cleanups required.
378void SROA::CanonicalizeAllocaUsers(AllocationInst *AI) {
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000379 // At this point, we know that the end result will be SROA'd and promoted, so
380 // we can insert ugly code if required so long as sroa+mem2reg will clean it
381 // up.
382 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
383 UI != E; ) {
384 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(*UI++);
Reid Spencer93396382004-11-15 17:29:41 +0000385 gep_type_iterator I = gep_type_begin(GEPI);
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000386 ++I;
Chris Lattner88819122004-11-14 04:24:28 +0000387
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000388 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
389 uint64_t NumElements = AT->getNumElements();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000390
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000391 if (!isa<ConstantInt>(I.getOperand())) {
392 if (NumElements == 1) {
Reid Spencerc635f472006-12-31 05:48:39 +0000393 GEPI->setOperand(2, Constant::getNullValue(Type::Int32Ty));
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000394 } else {
395 assert(NumElements == 2 && "Unhandled case!");
396 // All users of the GEP must be loads. At each use of the GEP, insert
397 // two loads of the appropriate indexed GEP and select between them.
Reid Spencer266e42b2006-12-23 06:05:41 +0000398 Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(),
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000399 Constant::getNullValue(I.getOperand()->getType()),
Reid Spencer266e42b2006-12-23 06:05:41 +0000400 "isone", GEPI);
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000401 // Insert the new GEP instructions, which are properly indexed.
Chris Lattnera7315132007-02-12 22:56:41 +0000402 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
Reid Spencerc635f472006-12-31 05:48:39 +0000403 Indices[1] = Constant::getNullValue(Type::Int32Ty);
Chris Lattnera7315132007-02-12 22:56:41 +0000404 Value *ZeroIdx = new GetElementPtrInst(GEPI->getOperand(0),
405 &Indices[0], Indices.size(),
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000406 GEPI->getName()+".0", GEPI);
Reid Spencerc635f472006-12-31 05:48:39 +0000407 Indices[1] = ConstantInt::get(Type::Int32Ty, 1);
Chris Lattnera7315132007-02-12 22:56:41 +0000408 Value *OneIdx = new GetElementPtrInst(GEPI->getOperand(0),
409 &Indices[0], Indices.size(),
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000410 GEPI->getName()+".1", GEPI);
411 // Replace all loads of the variable index GEP with loads from both
412 // indexes and a select.
413 while (!GEPI->use_empty()) {
414 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
415 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
416 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
417 Value *R = new SelectInst(IsOne, One, Zero, LI->getName(), LI);
418 LI->replaceAllUsesWith(R);
419 LI->eraseFromParent();
420 }
421 GEPI->eraseFromParent();
422 }
423 }
424 }
425 }
Chris Lattner6e5398d2003-05-30 04:15:41 +0000426}
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000427
428/// MergeInType - Add the 'In' type to the accumulated type so far. If the
429/// types are incompatible, return true, otherwise update Accum and return
430/// false.
Chris Lattner3323ce12006-04-14 21:42:41 +0000431///
Chris Lattner8f7b7752006-12-15 07:32:38 +0000432/// There are three cases we handle here:
433/// 1) An effectively-integer union, where the pieces are stored into as
Chris Lattner3323ce12006-04-14 21:42:41 +0000434/// smaller integers (common with byte swap and other idioms).
Chris Lattner8f7b7752006-12-15 07:32:38 +0000435/// 2) A union of vector types of the same size and potentially its elements.
436/// Here we turn element accesses into insert/extract element operations.
437/// 3) A union of scalar types, such as int/float or int/pointer. Here we
438/// merge together into integers, allowing the xform to work with #1 as
439/// well.
Chris Lattner05f82722006-10-08 23:28:04 +0000440static bool MergeInType(const Type *In, const Type *&Accum,
441 const TargetData &TD) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000442 // If this is our first type, just use it.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000443 const VectorType *PTy;
Chris Lattner3323ce12006-04-14 21:42:41 +0000444 if (Accum == Type::VoidTy || In == Accum) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000445 Accum = In;
Chris Lattner8f7b7752006-12-15 07:32:38 +0000446 } else if (In == Type::VoidTy) {
447 // Noop.
Chris Lattner03c49532007-01-15 02:27:26 +0000448 } else if (In->isInteger() && Accum->isInteger()) { // integer union.
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000449 // Otherwise pick whichever type is larger.
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000450 if (cast<IntegerType>(In)->getBitWidth() >
451 cast<IntegerType>(Accum)->getBitWidth())
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000452 Accum = In;
Chris Lattner05f82722006-10-08 23:28:04 +0000453 } else if (isa<PointerType>(In) && isa<PointerType>(Accum)) {
Chris Lattner41b44222006-10-08 23:53:04 +0000454 // Pointer unions just stay as one of the pointers.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000455 } else if (isa<VectorType>(In) || isa<VectorType>(Accum)) {
456 if ((PTy = dyn_cast<VectorType>(Accum)) &&
Chris Lattner8f7b7752006-12-15 07:32:38 +0000457 PTy->getElementType() == In) {
458 // Accum is a vector, and we are accessing an element: ok.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000459 } else if ((PTy = dyn_cast<VectorType>(In)) &&
Chris Lattner8f7b7752006-12-15 07:32:38 +0000460 PTy->getElementType() == Accum) {
461 // In is a vector, and accum is an element: ok, remember In.
462 Accum = In;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000463 } else if ((PTy = dyn_cast<VectorType>(In)) && isa<VectorType>(Accum) &&
464 PTy->getBitWidth() == cast<VectorType>(Accum)->getBitWidth()) {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000465 // Two vectors of the same size: keep Accum.
466 } else {
467 // Cannot insert an short into a <4 x int> or handle
468 // <2 x int> -> <4 x int>
469 return true;
470 }
Chris Lattner7c1dff92006-12-13 02:26:45 +0000471 } else {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000472 // Pointer/FP/Integer unions merge together as integers.
473 switch (Accum->getTypeID()) {
474 case Type::PointerTyID: Accum = TD.getIntPtrType(); break;
Reid Spencerc635f472006-12-31 05:48:39 +0000475 case Type::FloatTyID: Accum = Type::Int32Ty; break;
476 case Type::DoubleTyID: Accum = Type::Int64Ty; break;
Chris Lattner8f7b7752006-12-15 07:32:38 +0000477 default:
Chris Lattner03c49532007-01-15 02:27:26 +0000478 assert(Accum->isInteger() && "Unknown FP type!");
Chris Lattner8f7b7752006-12-15 07:32:38 +0000479 break;
480 }
481
482 switch (In->getTypeID()) {
483 case Type::PointerTyID: In = TD.getIntPtrType(); break;
Reid Spencerc635f472006-12-31 05:48:39 +0000484 case Type::FloatTyID: In = Type::Int32Ty; break;
485 case Type::DoubleTyID: In = Type::Int64Ty; break;
Chris Lattner8f7b7752006-12-15 07:32:38 +0000486 default:
Chris Lattner03c49532007-01-15 02:27:26 +0000487 assert(In->isInteger() && "Unknown FP type!");
Chris Lattner8f7b7752006-12-15 07:32:38 +0000488 break;
489 }
490 return MergeInType(In, Accum, TD);
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000491 }
492 return false;
493}
494
495/// getUIntAtLeastAsBitAs - Return an unsigned integer type that is at least
496/// as big as the specified type. If there is no suitable type, this returns
497/// null.
498const Type *getUIntAtLeastAsBitAs(unsigned NumBits) {
499 if (NumBits > 64) return 0;
Reid Spencerc635f472006-12-31 05:48:39 +0000500 if (NumBits > 32) return Type::Int64Ty;
501 if (NumBits > 16) return Type::Int32Ty;
502 if (NumBits > 8) return Type::Int16Ty;
503 return Type::Int8Ty;
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000504}
505
506/// CanConvertToScalar - V is a pointer. If we can convert the pointee to a
507/// single scalar integer type, return that type. Further, if the use is not
508/// a completely trivial use that mem2reg could promote, set IsNotTrivial. If
509/// there are no uses of this pointer, return Type::VoidTy to differentiate from
510/// failure.
511///
512const Type *SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial) {
513 const Type *UsedType = Type::VoidTy; // No uses, no forced type.
514 const TargetData &TD = getAnalysis<TargetData>();
515 const PointerType *PTy = cast<PointerType>(V->getType());
516
517 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
518 Instruction *User = cast<Instruction>(*UI);
519
520 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner05f82722006-10-08 23:28:04 +0000521 if (MergeInType(LI->getType(), UsedType, TD))
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000522 return 0;
523
524 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Reid Spencer2eadb532007-01-21 00:29:26 +0000525 // Storing the pointer, not into the value?
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000526 if (SI->getOperand(0) == V) return 0;
527
Chris Lattner3323ce12006-04-14 21:42:41 +0000528 // NOTE: We could handle storing of FP imms into integers here!
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000529
Chris Lattner05f82722006-10-08 23:28:04 +0000530 if (MergeInType(SI->getOperand(0)->getType(), UsedType, TD))
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000531 return 0;
Chris Lattner8f7b7752006-12-15 07:32:38 +0000532 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000533 IsNotTrivial = true;
534 const Type *SubTy = CanConvertToScalar(CI, IsNotTrivial);
Chris Lattner05f82722006-10-08 23:28:04 +0000535 if (!SubTy || MergeInType(SubTy, UsedType, TD)) return 0;
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000536 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
537 // Check to see if this is stepping over an element: GEP Ptr, int C
538 if (GEP->getNumOperands() == 2 && isa<ConstantInt>(GEP->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000539 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000540 unsigned ElSize = TD.getTypeSize(PTy->getElementType());
541 unsigned BitOffset = Idx*ElSize*8;
542 if (BitOffset > 64 || !isPowerOf2_32(ElSize)) return 0;
543
544 IsNotTrivial = true;
545 const Type *SubElt = CanConvertToScalar(GEP, IsNotTrivial);
546 if (SubElt == 0) return 0;
Chris Lattner03c49532007-01-15 02:27:26 +0000547 if (SubElt != Type::VoidTy && SubElt->isInteger()) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000548 const Type *NewTy =
Chris Lattner41b44222006-10-08 23:53:04 +0000549 getUIntAtLeastAsBitAs(TD.getTypeSize(SubElt)*8+BitOffset);
Chris Lattner05f82722006-10-08 23:28:04 +0000550 if (NewTy == 0 || MergeInType(NewTy, UsedType, TD)) return 0;
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000551 continue;
552 }
553 } else if (GEP->getNumOperands() == 3 &&
554 isa<ConstantInt>(GEP->getOperand(1)) &&
555 isa<ConstantInt>(GEP->getOperand(2)) &&
556 cast<Constant>(GEP->getOperand(1))->isNullValue()) {
557 // We are stepping into an element, e.g. a structure or an array:
558 // GEP Ptr, int 0, uint C
559 const Type *AggTy = PTy->getElementType();
Reid Spencere0fc4df2006-10-20 07:07:24 +0000560 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000561
562 if (const ArrayType *ATy = dyn_cast<ArrayType>(AggTy)) {
563 if (Idx >= ATy->getNumElements()) return 0; // Out of range.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000564 } else if (const VectorType *PackedTy = dyn_cast<VectorType>(AggTy)) {
Chris Lattner3323ce12006-04-14 21:42:41 +0000565 // Getting an element of the packed vector.
566 if (Idx >= PackedTy->getNumElements()) return 0; // Out of range.
567
568 // Merge in the packed type.
Chris Lattner05f82722006-10-08 23:28:04 +0000569 if (MergeInType(PackedTy, UsedType, TD)) return 0;
Chris Lattner3323ce12006-04-14 21:42:41 +0000570
571 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
572 if (SubTy == 0) return 0;
573
Chris Lattner05f82722006-10-08 23:28:04 +0000574 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
Chris Lattner3323ce12006-04-14 21:42:41 +0000575 return 0;
576
577 // We'll need to change this to an insert/extract element operation.
578 IsNotTrivial = true;
579 continue; // Everything looks ok
580
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000581 } else if (isa<StructType>(AggTy)) {
582 // Structs are always ok.
583 } else {
584 return 0;
585 }
586 const Type *NTy = getUIntAtLeastAsBitAs(TD.getTypeSize(AggTy)*8);
Chris Lattner05f82722006-10-08 23:28:04 +0000587 if (NTy == 0 || MergeInType(NTy, UsedType, TD)) return 0;
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000588 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
589 if (SubTy == 0) return 0;
Chris Lattner05f82722006-10-08 23:28:04 +0000590 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000591 return 0;
592 continue; // Everything looks ok
593 }
594 return 0;
595 } else {
596 // Cannot handle this!
597 return 0;
598 }
599 }
600
601 return UsedType;
602}
603
604/// ConvertToScalar - The specified alloca passes the CanConvertToScalar
605/// predicate and is non-trivial. Convert it to something that can be trivially
606/// promoted into a register by mem2reg.
607void SROA::ConvertToScalar(AllocationInst *AI, const Type *ActualTy) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000608 DOUT << "CONVERT TO SCALAR: " << *AI << " TYPE = "
609 << *ActualTy << "\n";
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000610 ++NumConverted;
611
612 BasicBlock *EntryBlock = AI->getParent();
613 assert(EntryBlock == &EntryBlock->getParent()->front() &&
614 "Not in the entry block!");
615 EntryBlock->getInstList().remove(AI); // Take the alloca out of the program.
616
617 // Create and insert the alloca.
Chris Lattner3323ce12006-04-14 21:42:41 +0000618 AllocaInst *NewAI = new AllocaInst(ActualTy, 0, AI->getName(),
619 EntryBlock->begin());
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000620 ConvertUsesToScalar(AI, NewAI, 0);
621 delete AI;
622}
623
624
625/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
Chris Lattner3323ce12006-04-14 21:42:41 +0000626/// directly. This happens when we are converting an "integer union" to a
627/// single integer scalar, or when we are converting a "vector union" to a
628/// vector with insert/extractelement instructions.
629///
630/// Offset is an offset from the original alloca, in bits that need to be
631/// shifted to the right. By the end of this, there should be no uses of Ptr.
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000632void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000633 bool isVectorInsert = isa<VectorType>(NewAI->getType()->getElementType());
Chris Lattner41b44222006-10-08 23:53:04 +0000634 const TargetData &TD = getAnalysis<TargetData>();
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000635 while (!Ptr->use_empty()) {
636 Instruction *User = cast<Instruction>(Ptr->use_back());
637
638 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
639 // The load is a bit extract from NewAI shifted right by Offset bits.
640 Value *NV = new LoadInst(NewAI, LI->getName(), LI);
Chris Lattner3323ce12006-04-14 21:42:41 +0000641 if (NV->getType() != LI->getType()) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000642 if (const VectorType *PTy = dyn_cast<VectorType>(NV->getType())) {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000643 // If the result alloca is a packed type, this is either an element
644 // access or a bitcast to another packed type.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000645 if (isa<VectorType>(LI->getType())) {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000646 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
Chris Lattner216c3022006-12-10 23:56:50 +0000647 } else {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000648 // Must be an element access.
649 unsigned Elt = Offset/(TD.getTypeSize(PTy->getElementType())*8);
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000650 NV = new ExtractElementInst(
651 NV, ConstantInt::get(Type::Int32Ty, Elt), "tmp", LI);
Chris Lattner216c3022006-12-10 23:56:50 +0000652 }
Chris Lattner8f7b7752006-12-15 07:32:38 +0000653 } else if (isa<PointerType>(NV->getType())) {
654 assert(isa<PointerType>(LI->getType()));
655 // Must be ptr->ptr cast. Anything else would result in NV being
656 // an integer.
657 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
658 } else {
Chris Lattner03c49532007-01-15 02:27:26 +0000659 assert(NV->getType()->isInteger() && "Unknown promotion!");
Chris Lattner8f7b7752006-12-15 07:32:38 +0000660 if (Offset && Offset < TD.getTypeSize(NV->getType())*8) {
Reid Spencer0d5f9232007-02-02 14:08:20 +0000661 NV = BinaryOperator::createLShr(NV,
Reid Spencer2341c222007-02-02 02:16:23 +0000662 ConstantInt::get(NV->getType(), Offset),
663 LI->getName(), LI);
Chris Lattner8f7b7752006-12-15 07:32:38 +0000664 }
665
666 // If the result is an integer, this is a trunc or bitcast.
Chris Lattner03c49532007-01-15 02:27:26 +0000667 if (LI->getType()->isInteger()) {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000668 NV = CastInst::createTruncOrBitCast(NV, LI->getType(),
669 LI->getName(), LI);
670 } else if (LI->getType()->isFloatingPoint()) {
671 // If needed, truncate the integer to the appropriate size.
Reid Spencer8f166b02007-01-08 16:32:00 +0000672 if (NV->getType()->getPrimitiveSizeInBits() >
673 LI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000674 switch (LI->getType()->getTypeID()) {
675 default: assert(0 && "Unknown FP type!");
676 case Type::FloatTyID:
Reid Spencerc635f472006-12-31 05:48:39 +0000677 NV = new TruncInst(NV, Type::Int32Ty, LI->getName(), LI);
Chris Lattner8f7b7752006-12-15 07:32:38 +0000678 break;
679 case Type::DoubleTyID:
Reid Spencerc635f472006-12-31 05:48:39 +0000680 NV = new TruncInst(NV, Type::Int64Ty, LI->getName(), LI);
Chris Lattner8f7b7752006-12-15 07:32:38 +0000681 break;
682 }
683 }
684
685 // Then do a bitcast.
686 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
687 } else {
688 // Otherwise must be a pointer.
689 NV = new IntToPtrInst(NV, LI->getType(), LI->getName(), LI);
690 }
Chris Lattner3323ce12006-04-14 21:42:41 +0000691 }
692 }
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000693 LI->replaceAllUsesWith(NV);
694 LI->eraseFromParent();
695 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
696 assert(SI->getOperand(0) != Ptr && "Consistency error!");
697
698 // Convert the stored type to the actual type, shift it left to insert
699 // then 'or' into place.
700 Value *SV = SI->getOperand(0);
Chris Lattner3323ce12006-04-14 21:42:41 +0000701 const Type *AllocaType = NewAI->getType()->getElementType();
702 if (SV->getType() != AllocaType) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000703 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
Chris Lattner3323ce12006-04-14 21:42:41 +0000704
Reid Spencerd84d35b2007-02-15 02:26:10 +0000705 if (const VectorType *PTy = dyn_cast<VectorType>(AllocaType)) {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000706 // If the result alloca is a packed type, this is either an element
707 // access or a bitcast to another packed type.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000708 if (isa<VectorType>(SV->getType())) {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000709 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
710 } else {
711 // Must be an element insertion.
712 unsigned Elt = Offset/(TD.getTypeSize(PTy->getElementType())*8);
713 SV = new InsertElementInst(Old, SV,
Reid Spencerc635f472006-12-31 05:48:39 +0000714 ConstantInt::get(Type::Int32Ty, Elt),
Chris Lattner8f7b7752006-12-15 07:32:38 +0000715 "tmp", SI);
716 }
Chris Lattner3323ce12006-04-14 21:42:41 +0000717 } else {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000718 // If SV is a float, convert it to the appropriate integer type.
719 // If it is a pointer, do the same, and also handle ptr->ptr casts
720 // here.
721 switch (SV->getType()->getTypeID()) {
722 default:
723 assert(!SV->getType()->isFloatingPoint() && "Unknown FP type!");
724 break;
725 case Type::FloatTyID:
Reid Spencerc635f472006-12-31 05:48:39 +0000726 SV = new BitCastInst(SV, Type::Int32Ty, SV->getName(), SI);
Chris Lattner8f7b7752006-12-15 07:32:38 +0000727 break;
728 case Type::DoubleTyID:
Reid Spencerc635f472006-12-31 05:48:39 +0000729 SV = new BitCastInst(SV, Type::Int64Ty, SV->getName(), SI);
Chris Lattner8f7b7752006-12-15 07:32:38 +0000730 break;
731 case Type::PointerTyID:
732 if (isa<PointerType>(AllocaType))
733 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
734 else
735 SV = new PtrToIntInst(SV, TD.getIntPtrType(), SV->getName(), SI);
736 break;
737 }
738
739 unsigned SrcSize = TD.getTypeSize(SV->getType())*8;
740
741 // Always zero extend the value if needed.
742 if (SV->getType() != AllocaType)
743 SV = CastInst::createZExtOrBitCast(SV, AllocaType,
744 SV->getName(), SI);
745 if (Offset && Offset < AllocaType->getPrimitiveSizeInBits())
Reid Spencer0d5f9232007-02-02 14:08:20 +0000746 SV = BinaryOperator::createShl(SV,
Reid Spencer2341c222007-02-02 02:16:23 +0000747 ConstantInt::get(SV->getType(), Offset),
748 SV->getName()+".adj", SI);
Chris Lattner3323ce12006-04-14 21:42:41 +0000749 // Mask out the bits we are about to insert from the old value.
Chris Lattner41b44222006-10-08 23:53:04 +0000750 unsigned TotalBits = TD.getTypeSize(SV->getType())*8;
Chris Lattner8f7b7752006-12-15 07:32:38 +0000751 if (TotalBits != SrcSize) {
752 assert(TotalBits > SrcSize);
753 uint64_t Mask = ~(((1ULL << SrcSize)-1) << Offset);
Reid Spencera94d3942007-01-19 21:13:56 +0000754 Mask = Mask & cast<IntegerType>(SV->getType())->getBitMask();
Chris Lattner3323ce12006-04-14 21:42:41 +0000755 Old = BinaryOperator::createAnd(Old,
Reid Spencere0fc4df2006-10-20 07:07:24 +0000756 ConstantInt::get(Old->getType(), Mask),
Chris Lattner3323ce12006-04-14 21:42:41 +0000757 Old->getName()+".mask", SI);
758 SV = BinaryOperator::createOr(Old, SV, SV->getName()+".ins", SI);
759 }
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000760 }
761 }
762 new StoreInst(SV, NewAI, SI);
763 SI->eraseFromParent();
764
765 } else if (CastInst *CI = dyn_cast<CastInst>(User)) {
766 unsigned NewOff = Offset;
767 const TargetData &TD = getAnalysis<TargetData>();
Chris Lattner3323ce12006-04-14 21:42:41 +0000768 if (TD.isBigEndian() && !isVectorInsert) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000769 // Adjust the pointer. For example, storing 16-bits into a 32-bit
770 // alloca with just a cast makes it modify the top 16-bits.
771 const Type *SrcTy = cast<PointerType>(Ptr->getType())->getElementType();
772 const Type *DstTy = cast<PointerType>(CI->getType())->getElementType();
773 int PtrDiffBits = TD.getTypeSize(SrcTy)*8-TD.getTypeSize(DstTy)*8;
774 NewOff += PtrDiffBits;
775 }
776 ConvertUsesToScalar(CI, NewAI, NewOff);
777 CI->eraseFromParent();
778 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
779 const PointerType *AggPtrTy =
780 cast<PointerType>(GEP->getOperand(0)->getType());
781 const TargetData &TD = getAnalysis<TargetData>();
782 unsigned AggSizeInBits = TD.getTypeSize(AggPtrTy->getElementType())*8;
783
784 // Check to see if this is stepping over an element: GEP Ptr, int C
785 unsigned NewOffset = Offset;
786 if (GEP->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000787 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000788 unsigned BitOffset = Idx*AggSizeInBits;
789
Chris Lattner3323ce12006-04-14 21:42:41 +0000790 if (TD.isLittleEndian() || isVectorInsert)
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000791 NewOffset += BitOffset;
792 else
793 NewOffset -= BitOffset;
794
795 } else if (GEP->getNumOperands() == 3) {
796 // We know that operand #2 is zero.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000797 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000798 const Type *AggTy = AggPtrTy->getElementType();
799 if (const SequentialType *SeqTy = dyn_cast<SequentialType>(AggTy)) {
800 unsigned ElSizeBits = TD.getTypeSize(SeqTy->getElementType())*8;
801
Chris Lattner3323ce12006-04-14 21:42:41 +0000802 if (TD.isLittleEndian() || isVectorInsert)
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000803 NewOffset += ElSizeBits*Idx;
804 else
805 NewOffset += AggSizeInBits-ElSizeBits*(Idx+1);
806 } else if (const StructType *STy = dyn_cast<StructType>(AggTy)) {
Chris Lattnerc473d8e2007-02-10 19:55:17 +0000807 unsigned EltBitOffset =
808 TD.getStructLayout(STy)->getElementOffset(Idx)*8;
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000809
Chris Lattner3323ce12006-04-14 21:42:41 +0000810 if (TD.isLittleEndian() || isVectorInsert)
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000811 NewOffset += EltBitOffset;
812 else {
813 const PointerType *ElPtrTy = cast<PointerType>(GEP->getType());
814 unsigned ElSizeBits = TD.getTypeSize(ElPtrTy->getElementType())*8;
815 NewOffset += AggSizeInBits-(EltBitOffset+ElSizeBits);
816 }
817
818 } else {
819 assert(0 && "Unsupported operation!");
820 abort();
821 }
822 } else {
823 assert(0 && "Unsupported operation!");
824 abort();
825 }
826 ConvertUsesToScalar(GEP, NewAI, NewOffset);
827 GEP->eraseFromParent();
828 } else {
829 assert(0 && "Unsupported operation!");
830 abort();
831 }
832 }
833}