blob: e241c01e3bc50399203488cbced5d2ceb67c3d7f [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"
Reid Spencer7c16caa2004-09-01 22:55:40 +000036#include "llvm/ADT/Statistic.h"
37#include "llvm/ADT/StringExtras.h"
Chris Lattner40d2aeb2003-12-02 17:43:55 +000038using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000039
Chris Lattner79a42ac2006-12-19 21:40:18 +000040STATISTIC(NumReplaced, "Number of allocas broken up");
41STATISTIC(NumPromoted, "Number of allocas promoted");
42STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattnerfb41a502003-05-27 15:45:27 +000043
Chris Lattner79a42ac2006-12-19 21:40:18 +000044namespace {
Chris Lattner996795b2006-06-28 23:17:24 +000045 struct VISIBILITY_HIDDEN SROA : public FunctionPass {
Chris Lattnerfb41a502003-05-27 15:45:27 +000046 bool runOnFunction(Function &F);
47
Chris Lattner5d8a12e2003-09-11 16:45:55 +000048 bool performScalarRepl(Function &F);
49 bool performPromotion(Function &F);
50
Chris Lattnerc8174582003-08-31 00:45:13 +000051 // getAnalysisUsage - This pass does not require any passes, but we know it
52 // will not alter the CFG, so say so.
53 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnera906bac2003-10-05 21:20:13 +000054 AU.addRequired<DominatorTree>();
Chris Lattner5d8a12e2003-09-11 16:45:55 +000055 AU.addRequired<DominanceFrontier>();
56 AU.addRequired<TargetData>();
Chris Lattnerc8174582003-08-31 00:45:13 +000057 AU.setPreservesCFG();
58 }
59
Chris Lattnerfb41a502003-05-27 15:45:27 +000060 private:
Chris Lattner88819122004-11-14 04:24:28 +000061 int isSafeElementUse(Value *Ptr);
62 int isSafeUseOfAllocation(Instruction *User);
63 int isSafeAllocaToScalarRepl(AllocationInst *AI);
64 void CanonicalizeAllocaUsers(AllocationInst *AI);
Chris Lattnerfb41a502003-05-27 15:45:27 +000065 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
Chris Lattner3b0a62d2005-12-12 07:19:13 +000066
67 const Type *CanConvertToScalar(Value *V, bool &IsNotTrivial);
68 void ConvertToScalar(AllocationInst *AI, const Type *Ty);
69 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset);
Chris Lattnerfb41a502003-05-27 15:45:27 +000070 };
71
Chris Lattnerc2d3d312006-08-27 22:42:52 +000072 RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
Chris Lattnerfb41a502003-05-27 15:45:27 +000073}
74
Brian Gaeke960707c2003-11-11 22:41:34 +000075// Public interface to the ScalarReplAggregates pass
Chris Lattner3e860842004-09-20 04:43:15 +000076FunctionPass *llvm::createScalarReplAggregatesPass() { return new SROA(); }
Chris Lattnerfb41a502003-05-27 15:45:27 +000077
78
Chris Lattnerfb41a502003-05-27 15:45:27 +000079bool SROA::runOnFunction(Function &F) {
Chris Lattner9a95f2a2003-09-12 15:36:03 +000080 bool Changed = performPromotion(F);
81 while (1) {
82 bool LocalChange = performScalarRepl(F);
83 if (!LocalChange) break; // No need to repromote if no scalarrepl
84 Changed = true;
85 LocalChange = performPromotion(F);
86 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
87 }
Chris Lattner5d8a12e2003-09-11 16:45:55 +000088
89 return Changed;
90}
91
92
93bool SROA::performPromotion(Function &F) {
94 std::vector<AllocaInst*> Allocas;
95 const TargetData &TD = getAnalysis<TargetData>();
Chris Lattnera906bac2003-10-05 21:20:13 +000096 DominatorTree &DT = getAnalysis<DominatorTree>();
97 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
Chris Lattner5d8a12e2003-09-11 16:45:55 +000098
Chris Lattner5dac64f2003-09-20 14:39:18 +000099 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000100
Chris Lattner9a95f2a2003-09-12 15:36:03 +0000101 bool Changed = false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000102
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000103 while (1) {
104 Allocas.clear();
105
106 // Find allocas that are safe to promote, by looking at all instructions in
107 // the entry node
108 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
109 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
110 if (isAllocaPromotable(AI, TD))
111 Allocas.push_back(AI);
112
113 if (Allocas.empty()) break;
114
Chris Lattnera906bac2003-10-05 21:20:13 +0000115 PromoteMemToReg(Allocas, DT, DF, TD);
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000116 NumPromoted += Allocas.size();
117 Changed = true;
118 }
119
120 return Changed;
121}
122
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000123// performScalarRepl - This algorithm is a simple worklist driven algorithm,
124// which runs on all of the malloc/alloca instructions in the function, removing
125// them if they are only used by getelementptr instructions.
126//
127bool SROA::performScalarRepl(Function &F) {
Chris Lattnerfb41a502003-05-27 15:45:27 +0000128 std::vector<AllocationInst*> WorkList;
129
130 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
Chris Lattner5dac64f2003-09-20 14:39:18 +0000131 BasicBlock &BB = F.getEntryBlock();
Chris Lattnerfb41a502003-05-27 15:45:27 +0000132 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
133 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
134 WorkList.push_back(A);
135
136 // Process the worklist
137 bool Changed = false;
138 while (!WorkList.empty()) {
139 AllocationInst *AI = WorkList.back();
140 WorkList.pop_back();
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000141
Chris Lattnerf171af92006-12-22 23:14:42 +0000142 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
143 // with unused elements.
144 if (AI->use_empty()) {
145 AI->eraseFromParent();
146 continue;
147 }
148
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000149 // If we can turn this aggregate value (potentially with casts) into a
150 // simple scalar value that can be mem2reg'd into a register value.
151 bool IsNotTrivial = false;
152 if (const Type *ActualType = CanConvertToScalar(AI, IsNotTrivial))
Chris Lattnerdae49df2006-04-20 20:48:50 +0000153 if (IsNotTrivial && ActualType != Type::VoidTy) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000154 ConvertToScalar(AI, ActualType);
155 Changed = true;
156 continue;
157 }
Chris Lattnerfb41a502003-05-27 15:45:27 +0000158
159 // We cannot transform the allocation instruction if it is an array
Chris Lattnerc16b2102003-05-27 16:09:27 +0000160 // allocation (allocations OF arrays are ok though), and an allocation of a
161 // scalar value cannot be decomposed at all.
162 //
Chris Lattnerfb41a502003-05-27 15:45:27 +0000163 if (AI->isArrayAllocation() ||
Chris Lattnerc16b2102003-05-27 16:09:27 +0000164 (!isa<StructType>(AI->getAllocatedType()) &&
165 !isa<ArrayType>(AI->getAllocatedType()))) continue;
166
Chris Lattner6e5398d2003-05-30 04:15:41 +0000167 // Check that all of the users of the allocation are capable of being
168 // transformed.
Chris Lattner88819122004-11-14 04:24:28 +0000169 switch (isSafeAllocaToScalarRepl(AI)) {
170 default: assert(0 && "Unexpected value!");
171 case 0: // Not safe to scalar replace.
Chris Lattner6e5398d2003-05-30 04:15:41 +0000172 continue;
Chris Lattner88819122004-11-14 04:24:28 +0000173 case 1: // Safe, but requires cleanup/canonicalizations first
174 CanonicalizeAllocaUsers(AI);
175 case 3: // Safe to scalar replace.
176 break;
177 }
Chris Lattnerfb41a502003-05-27 15:45:27 +0000178
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000179 DOUT << "Found inst to xform: " << *AI;
Chris Lattnerfb41a502003-05-27 15:45:27 +0000180 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000181
Chris Lattnerfb41a502003-05-27 15:45:27 +0000182 std::vector<AllocaInst*> ElementAllocas;
183 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
184 ElementAllocas.reserve(ST->getNumContainedTypes());
185 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Nate Begeman848622f2005-11-05 09:21:28 +0000186 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
187 AI->getAlignment(),
Chris Lattnerfb41a502003-05-27 15:45:27 +0000188 AI->getName() + "." + utostr(i), AI);
189 ElementAllocas.push_back(NA);
190 WorkList.push_back(NA); // Add to worklist for recursive processing
191 }
192 } else {
Chris Lattner6e5398d2003-05-30 04:15:41 +0000193 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
Chris Lattnerfb41a502003-05-27 15:45:27 +0000194 ElementAllocas.reserve(AT->getNumElements());
195 const Type *ElTy = AT->getElementType();
196 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Nate Begeman848622f2005-11-05 09:21:28 +0000197 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Chris Lattnerfb41a502003-05-27 15:45:27 +0000198 AI->getName() + "." + utostr(i), AI);
199 ElementAllocas.push_back(NA);
200 WorkList.push_back(NA); // Add to worklist for recursive processing
201 }
202 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000203
Chris Lattnerfb41a502003-05-27 15:45:27 +0000204 // Now that we have created the alloca instructions that we want to use,
205 // expand the getelementptr instructions to use them.
206 //
Chris Lattnerb5f8eb82004-06-19 02:02:22 +0000207 while (!AI->use_empty()) {
208 Instruction *User = cast<Instruction>(AI->use_back());
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000209 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
210 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
Misha Brukmanb1c93172005-04-21 23:48:37 +0000211 unsigned Idx =
Reid Spencere0fc4df2006-10-20 07:07:24 +0000212 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000213
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000214 assert(Idx < ElementAllocas.size() && "Index out of range?");
215 AllocaInst *AllocaToUse = ElementAllocas[Idx];
Misha Brukmanb1c93172005-04-21 23:48:37 +0000216
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000217 Value *RepValue;
218 if (GEPI->getNumOperands() == 3) {
219 // Do not insert a new getelementptr instruction with zero indices, only
220 // to have it optimized out later.
221 RepValue = AllocaToUse;
Chris Lattnerfb41a502003-05-27 15:45:27 +0000222 } else {
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000223 // We are indexing deeply into the structure, so we still need a
224 // getelement ptr instruction to finish the indexing. This may be
225 // expanded itself once the worklist is rerun.
226 //
227 std::string OldName = GEPI->getName(); // Steal the old name.
228 std::vector<Value*> NewArgs;
Reid Spencerc635f472006-12-31 05:48:39 +0000229 NewArgs.push_back(Constant::getNullValue(Type::Int32Ty));
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000230 NewArgs.insert(NewArgs.end(), GEPI->op_begin()+3, GEPI->op_end());
231 GEPI->setName("");
232 RepValue = new GetElementPtrInst(AllocaToUse, NewArgs, OldName, GEPI);
Chris Lattnerfb41a502003-05-27 15:45:27 +0000233 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000234
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000235 // Move all of the users over to the new GEP.
236 GEPI->replaceAllUsesWith(RepValue);
237 // Delete the old GEP
238 GEPI->eraseFromParent();
Chris Lattnerfb41a502003-05-27 15:45:27 +0000239 }
240
241 // Finally, delete the Alloca instruction
Chris Lattnerf171af92006-12-22 23:14:42 +0000242 AI->eraseFromParent();
Chris Lattnerc16b2102003-05-27 16:09:27 +0000243 NumReplaced++;
Chris Lattnerfb41a502003-05-27 15:45:27 +0000244 }
245
246 return Changed;
247}
Chris Lattner6e5398d2003-05-30 04:15:41 +0000248
249
Chris Lattner88819122004-11-14 04:24:28 +0000250/// isSafeElementUse - Check to see if this use is an allowed use for a
251/// getelementptr instruction of an array aggregate allocation.
252///
253int SROA::isSafeElementUse(Value *Ptr) {
254 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
255 I != E; ++I) {
256 Instruction *User = cast<Instruction>(*I);
257 switch (User->getOpcode()) {
258 case Instruction::Load: break;
259 case Instruction::Store:
260 // Store is ok if storing INTO the pointer, not storing the pointer
261 if (User->getOperand(0) == Ptr) return 0;
262 break;
263 case Instruction::GetElementPtr: {
264 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
265 if (GEP->getNumOperands() > 1) {
266 if (!isa<Constant>(GEP->getOperand(1)) ||
267 !cast<Constant>(GEP->getOperand(1))->isNullValue())
268 return 0; // Using pointer arithmetic to navigate the array...
269 }
270 if (!isSafeElementUse(GEP)) return 0;
271 break;
272 }
273 default:
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000274 DOUT << " Transformation preventing inst: " << *User;
Chris Lattner88819122004-11-14 04:24:28 +0000275 return 0;
276 }
277 }
278 return 3; // All users look ok :)
279}
280
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000281/// AllUsersAreLoads - Return true if all users of this value are loads.
282static bool AllUsersAreLoads(Value *Ptr) {
283 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
284 I != E; ++I)
285 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
286 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000287 return true;
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000288}
289
Chris Lattner6e5398d2003-05-30 04:15:41 +0000290/// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
291/// aggregate allocation.
292///
Chris Lattner88819122004-11-14 04:24:28 +0000293int SROA::isSafeUseOfAllocation(Instruction *User) {
294 if (!isa<GetElementPtrInst>(User)) return 0;
Chris Lattner52310702003-11-25 21:09:18 +0000295
296 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
297 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
298
Chris Lattnerfc34f8b2006-03-08 01:05:29 +0000299 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
Chris Lattner52310702003-11-25 21:09:18 +0000300 if (I == E ||
301 I.getOperand() != Constant::getNullValue(I.getOperand()->getType()))
Chris Lattner88819122004-11-14 04:24:28 +0000302 return 0;
Chris Lattner52310702003-11-25 21:09:18 +0000303
304 ++I;
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000305 if (I == E) return 0; // ran out of GEP indices??
Chris Lattner52310702003-11-25 21:09:18 +0000306
307 // If this is a use of an array allocation, do a bit more checking for sanity.
308 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
309 uint64_t NumElements = AT->getNumElements();
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000310
Reid Spencerde46e482006-11-02 20:25:50 +0000311 if (isa<ConstantInt>(I.getOperand())) {
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000312 // Check to make sure that index falls within the array. If not,
313 // something funny is going on, so we won't do the optimization.
314 //
Reid Spencere0fc4df2006-10-20 07:07:24 +0000315 if (cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue() >= NumElements)
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000316 return 0;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000317
Chris Lattnerfc34f8b2006-03-08 01:05:29 +0000318 // We cannot scalar repl this level of the array unless any array
319 // sub-indices are in-range constants. In particular, consider:
320 // A[0][i]. We cannot know that the user isn't doing invalid things like
321 // allowing i to index an out-of-range subscript that accesses A[1].
322 //
323 // Scalar replacing *just* the outer index of the array is probably not
324 // going to be a win anyway, so just give up.
Chris Lattner4967f6d2006-11-07 22:42:47 +0000325 for (++I; I != E && (isa<ArrayType>(*I) || isa<PackedType>(*I)); ++I) {
326 uint64_t NumElements;
327 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*I))
328 NumElements = SubArrayTy->getNumElements();
329 else
330 NumElements = cast<PackedType>(*I)->getNumElements();
331
Chris Lattnerfc34f8b2006-03-08 01:05:29 +0000332 if (!isa<ConstantInt>(I.getOperand())) return 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +0000333 if (cast<ConstantInt>(I.getOperand())->getZExtValue() >= NumElements)
Chris Lattnerfc34f8b2006-03-08 01:05:29 +0000334 return 0;
335 }
336
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000337 } else {
338 // If this is an array index and the index is not constant, we cannot
339 // promote... that is unless the array has exactly one or two elements in
340 // it, in which case we CAN promote it, but we have to canonicalize this
341 // out if this is the only problem.
Chris Lattnerfc34f8b2006-03-08 01:05:29 +0000342 if ((NumElements == 1 || NumElements == 2) &&
343 AllUsersAreLoads(GEPI))
344 return 1; // Canonicalization required!
Chris Lattner88819122004-11-14 04:24:28 +0000345 return 0;
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000346 }
Chris Lattner6e5398d2003-05-30 04:15:41 +0000347 }
Chris Lattner52310702003-11-25 21:09:18 +0000348
349 // If there are any non-simple uses of this getelementptr, make sure to reject
350 // them.
351 return isSafeElementUse(GEPI);
Chris Lattner6e5398d2003-05-30 04:15:41 +0000352}
353
Chris Lattner88819122004-11-14 04:24:28 +0000354/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
355/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
356/// or 1 if safe after canonicalization has been performed.
Chris Lattner6e5398d2003-05-30 04:15:41 +0000357///
Chris Lattner88819122004-11-14 04:24:28 +0000358int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
Chris Lattner6e5398d2003-05-30 04:15:41 +0000359 // Loop over the use list of the alloca. We can only transform it if all of
360 // the users are safe to transform.
361 //
Chris Lattner88819122004-11-14 04:24:28 +0000362 int isSafe = 3;
Chris Lattner6e5398d2003-05-30 04:15:41 +0000363 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
Chris Lattner88819122004-11-14 04:24:28 +0000364 I != E; ++I) {
365 isSafe &= isSafeUseOfAllocation(cast<Instruction>(*I));
366 if (isSafe == 0) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000367 DOUT << "Cannot transform: " << *AI << " due to user: " << **I;
Chris Lattner88819122004-11-14 04:24:28 +0000368 return 0;
Chris Lattner6e5398d2003-05-30 04:15:41 +0000369 }
Chris Lattner88819122004-11-14 04:24:28 +0000370 }
371 // If we require cleanup, isSafe is now 1, otherwise it is 3.
372 return isSafe;
373}
374
375/// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified
376/// allocation, but only if cleaned up, perform the cleanups required.
377void SROA::CanonicalizeAllocaUsers(AllocationInst *AI) {
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000378 // At this point, we know that the end result will be SROA'd and promoted, so
379 // we can insert ugly code if required so long as sroa+mem2reg will clean it
380 // up.
381 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
382 UI != E; ) {
383 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(*UI++);
Reid Spencer93396382004-11-15 17:29:41 +0000384 gep_type_iterator I = gep_type_begin(GEPI);
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000385 ++I;
Chris Lattner88819122004-11-14 04:24:28 +0000386
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000387 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
388 uint64_t NumElements = AT->getNumElements();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000389
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000390 if (!isa<ConstantInt>(I.getOperand())) {
391 if (NumElements == 1) {
Reid Spencerc635f472006-12-31 05:48:39 +0000392 GEPI->setOperand(2, Constant::getNullValue(Type::Int32Ty));
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000393 } else {
394 assert(NumElements == 2 && "Unhandled case!");
395 // All users of the GEP must be loads. At each use of the GEP, insert
396 // two loads of the appropriate indexed GEP and select between them.
Reid Spencer266e42b2006-12-23 06:05:41 +0000397 Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(),
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000398 Constant::getNullValue(I.getOperand()->getType()),
Reid Spencer266e42b2006-12-23 06:05:41 +0000399 "isone", GEPI);
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000400 // Insert the new GEP instructions, which are properly indexed.
401 std::vector<Value*> Indices(GEPI->op_begin()+1, GEPI->op_end());
Reid Spencerc635f472006-12-31 05:48:39 +0000402 Indices[1] = Constant::getNullValue(Type::Int32Ty);
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000403 Value *ZeroIdx = new GetElementPtrInst(GEPI->getOperand(0), Indices,
404 GEPI->getName()+".0", GEPI);
Reid Spencerc635f472006-12-31 05:48:39 +0000405 Indices[1] = ConstantInt::get(Type::Int32Ty, 1);
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000406 Value *OneIdx = new GetElementPtrInst(GEPI->getOperand(0), Indices,
407 GEPI->getName()+".1", GEPI);
408 // Replace all loads of the variable index GEP with loads from both
409 // indexes and a select.
410 while (!GEPI->use_empty()) {
411 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
412 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
413 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
414 Value *R = new SelectInst(IsOne, One, Zero, LI->getName(), LI);
415 LI->replaceAllUsesWith(R);
416 LI->eraseFromParent();
417 }
418 GEPI->eraseFromParent();
419 }
420 }
421 }
422 }
Chris Lattner6e5398d2003-05-30 04:15:41 +0000423}
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000424
425/// MergeInType - Add the 'In' type to the accumulated type so far. If the
426/// types are incompatible, return true, otherwise update Accum and return
427/// false.
Chris Lattner3323ce12006-04-14 21:42:41 +0000428///
Chris Lattner8f7b7752006-12-15 07:32:38 +0000429/// There are three cases we handle here:
430/// 1) An effectively-integer union, where the pieces are stored into as
Chris Lattner3323ce12006-04-14 21:42:41 +0000431/// smaller integers (common with byte swap and other idioms).
Chris Lattner8f7b7752006-12-15 07:32:38 +0000432/// 2) A union of vector types of the same size and potentially its elements.
433/// Here we turn element accesses into insert/extract element operations.
434/// 3) A union of scalar types, such as int/float or int/pointer. Here we
435/// merge together into integers, allowing the xform to work with #1 as
436/// well.
Chris Lattner05f82722006-10-08 23:28:04 +0000437static bool MergeInType(const Type *In, const Type *&Accum,
438 const TargetData &TD) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000439 // If this is our first type, just use it.
Chris Lattner3323ce12006-04-14 21:42:41 +0000440 const PackedType *PTy;
441 if (Accum == Type::VoidTy || In == Accum) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000442 Accum = In;
Chris Lattner8f7b7752006-12-15 07:32:38 +0000443 } else if (In == Type::VoidTy) {
444 // Noop.
Chris Lattner03c49532007-01-15 02:27:26 +0000445 } else if (In->isInteger() && Accum->isInteger()) { // integer union.
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000446 // Otherwise pick whichever type is larger.
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000447 if (cast<IntegerType>(In)->getBitWidth() >
448 cast<IntegerType>(Accum)->getBitWidth())
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000449 Accum = In;
Chris Lattner05f82722006-10-08 23:28:04 +0000450 } else if (isa<PointerType>(In) && isa<PointerType>(Accum)) {
Chris Lattner41b44222006-10-08 23:53:04 +0000451 // Pointer unions just stay as one of the pointers.
Chris Lattner8f7b7752006-12-15 07:32:38 +0000452 } else if (isa<PackedType>(In) || isa<PackedType>(Accum)) {
453 if ((PTy = dyn_cast<PackedType>(Accum)) &&
454 PTy->getElementType() == In) {
455 // Accum is a vector, and we are accessing an element: ok.
456 } else if ((PTy = dyn_cast<PackedType>(In)) &&
457 PTy->getElementType() == Accum) {
458 // In is a vector, and accum is an element: ok, remember In.
459 Accum = In;
460 } else if ((PTy = dyn_cast<PackedType>(In)) && isa<PackedType>(Accum) &&
461 PTy->getBitWidth() == cast<PackedType>(Accum)->getBitWidth()) {
462 // Two vectors of the same size: keep Accum.
463 } else {
464 // Cannot insert an short into a <4 x int> or handle
465 // <2 x int> -> <4 x int>
466 return true;
467 }
Chris Lattner7c1dff92006-12-13 02:26:45 +0000468 } else {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000469 // Pointer/FP/Integer unions merge together as integers.
470 switch (Accum->getTypeID()) {
471 case Type::PointerTyID: Accum = TD.getIntPtrType(); break;
Reid Spencerc635f472006-12-31 05:48:39 +0000472 case Type::FloatTyID: Accum = Type::Int32Ty; break;
473 case Type::DoubleTyID: Accum = Type::Int64Ty; break;
Chris Lattner8f7b7752006-12-15 07:32:38 +0000474 default:
Chris Lattner03c49532007-01-15 02:27:26 +0000475 assert(Accum->isInteger() && "Unknown FP type!");
Chris Lattner8f7b7752006-12-15 07:32:38 +0000476 break;
477 }
478
479 switch (In->getTypeID()) {
480 case Type::PointerTyID: In = TD.getIntPtrType(); break;
Reid Spencerc635f472006-12-31 05:48:39 +0000481 case Type::FloatTyID: In = Type::Int32Ty; break;
482 case Type::DoubleTyID: In = Type::Int64Ty; break;
Chris Lattner8f7b7752006-12-15 07:32:38 +0000483 default:
Chris Lattner03c49532007-01-15 02:27:26 +0000484 assert(In->isInteger() && "Unknown FP type!");
Chris Lattner8f7b7752006-12-15 07:32:38 +0000485 break;
486 }
487 return MergeInType(In, Accum, TD);
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000488 }
489 return false;
490}
491
492/// getUIntAtLeastAsBitAs - Return an unsigned integer type that is at least
493/// as big as the specified type. If there is no suitable type, this returns
494/// null.
495const Type *getUIntAtLeastAsBitAs(unsigned NumBits) {
496 if (NumBits > 64) return 0;
Reid Spencerc635f472006-12-31 05:48:39 +0000497 if (NumBits > 32) return Type::Int64Ty;
498 if (NumBits > 16) return Type::Int32Ty;
499 if (NumBits > 8) return Type::Int16Ty;
500 return Type::Int8Ty;
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000501}
502
503/// CanConvertToScalar - V is a pointer. If we can convert the pointee to a
504/// single scalar integer type, return that type. Further, if the use is not
505/// a completely trivial use that mem2reg could promote, set IsNotTrivial. If
506/// there are no uses of this pointer, return Type::VoidTy to differentiate from
507/// failure.
508///
509const Type *SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial) {
510 const Type *UsedType = Type::VoidTy; // No uses, no forced type.
511 const TargetData &TD = getAnalysis<TargetData>();
512 const PointerType *PTy = cast<PointerType>(V->getType());
513
514 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
515 Instruction *User = cast<Instruction>(*UI);
516
517 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner05f82722006-10-08 23:28:04 +0000518 if (MergeInType(LI->getType(), UsedType, TD))
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000519 return 0;
520
521 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
522 // Storing the pointer, not the into the value?
523 if (SI->getOperand(0) == V) return 0;
524
Chris Lattner3323ce12006-04-14 21:42:41 +0000525 // NOTE: We could handle storing of FP imms into integers here!
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000526
Chris Lattner05f82722006-10-08 23:28:04 +0000527 if (MergeInType(SI->getOperand(0)->getType(), UsedType, TD))
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000528 return 0;
Chris Lattner8f7b7752006-12-15 07:32:38 +0000529 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000530 IsNotTrivial = true;
531 const Type *SubTy = CanConvertToScalar(CI, IsNotTrivial);
Chris Lattner05f82722006-10-08 23:28:04 +0000532 if (!SubTy || MergeInType(SubTy, UsedType, TD)) return 0;
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000533 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
534 // Check to see if this is stepping over an element: GEP Ptr, int C
535 if (GEP->getNumOperands() == 2 && isa<ConstantInt>(GEP->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000536 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000537 unsigned ElSize = TD.getTypeSize(PTy->getElementType());
538 unsigned BitOffset = Idx*ElSize*8;
539 if (BitOffset > 64 || !isPowerOf2_32(ElSize)) return 0;
540
541 IsNotTrivial = true;
542 const Type *SubElt = CanConvertToScalar(GEP, IsNotTrivial);
543 if (SubElt == 0) return 0;
Chris Lattner03c49532007-01-15 02:27:26 +0000544 if (SubElt != Type::VoidTy && SubElt->isInteger()) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000545 const Type *NewTy =
Chris Lattner41b44222006-10-08 23:53:04 +0000546 getUIntAtLeastAsBitAs(TD.getTypeSize(SubElt)*8+BitOffset);
Chris Lattner05f82722006-10-08 23:28:04 +0000547 if (NewTy == 0 || MergeInType(NewTy, UsedType, TD)) return 0;
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000548 continue;
549 }
550 } else if (GEP->getNumOperands() == 3 &&
551 isa<ConstantInt>(GEP->getOperand(1)) &&
552 isa<ConstantInt>(GEP->getOperand(2)) &&
553 cast<Constant>(GEP->getOperand(1))->isNullValue()) {
554 // We are stepping into an element, e.g. a structure or an array:
555 // GEP Ptr, int 0, uint C
556 const Type *AggTy = PTy->getElementType();
Reid Spencere0fc4df2006-10-20 07:07:24 +0000557 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000558
559 if (const ArrayType *ATy = dyn_cast<ArrayType>(AggTy)) {
560 if (Idx >= ATy->getNumElements()) return 0; // Out of range.
Chris Lattner3323ce12006-04-14 21:42:41 +0000561 } else if (const PackedType *PackedTy = dyn_cast<PackedType>(AggTy)) {
562 // Getting an element of the packed vector.
563 if (Idx >= PackedTy->getNumElements()) return 0; // Out of range.
564
565 // Merge in the packed type.
Chris Lattner05f82722006-10-08 23:28:04 +0000566 if (MergeInType(PackedTy, UsedType, TD)) return 0;
Chris Lattner3323ce12006-04-14 21:42:41 +0000567
568 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
569 if (SubTy == 0) return 0;
570
Chris Lattner05f82722006-10-08 23:28:04 +0000571 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
Chris Lattner3323ce12006-04-14 21:42:41 +0000572 return 0;
573
574 // We'll need to change this to an insert/extract element operation.
575 IsNotTrivial = true;
576 continue; // Everything looks ok
577
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000578 } else if (isa<StructType>(AggTy)) {
579 // Structs are always ok.
580 } else {
581 return 0;
582 }
583 const Type *NTy = getUIntAtLeastAsBitAs(TD.getTypeSize(AggTy)*8);
Chris Lattner05f82722006-10-08 23:28:04 +0000584 if (NTy == 0 || MergeInType(NTy, UsedType, TD)) return 0;
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000585 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
586 if (SubTy == 0) return 0;
Chris Lattner05f82722006-10-08 23:28:04 +0000587 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000588 return 0;
589 continue; // Everything looks ok
590 }
591 return 0;
592 } else {
593 // Cannot handle this!
594 return 0;
595 }
596 }
597
598 return UsedType;
599}
600
601/// ConvertToScalar - The specified alloca passes the CanConvertToScalar
602/// predicate and is non-trivial. Convert it to something that can be trivially
603/// promoted into a register by mem2reg.
604void SROA::ConvertToScalar(AllocationInst *AI, const Type *ActualTy) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000605 DOUT << "CONVERT TO SCALAR: " << *AI << " TYPE = "
606 << *ActualTy << "\n";
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000607 ++NumConverted;
608
609 BasicBlock *EntryBlock = AI->getParent();
610 assert(EntryBlock == &EntryBlock->getParent()->front() &&
611 "Not in the entry block!");
612 EntryBlock->getInstList().remove(AI); // Take the alloca out of the program.
613
614 // Create and insert the alloca.
Chris Lattner3323ce12006-04-14 21:42:41 +0000615 AllocaInst *NewAI = new AllocaInst(ActualTy, 0, AI->getName(),
616 EntryBlock->begin());
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000617 ConvertUsesToScalar(AI, NewAI, 0);
618 delete AI;
619}
620
621
622/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
Chris Lattner3323ce12006-04-14 21:42:41 +0000623/// directly. This happens when we are converting an "integer union" to a
624/// single integer scalar, or when we are converting a "vector union" to a
625/// vector with insert/extractelement instructions.
626///
627/// Offset is an offset from the original alloca, in bits that need to be
628/// shifted to the right. By the end of this, there should be no uses of Ptr.
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000629void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset) {
Chris Lattner3323ce12006-04-14 21:42:41 +0000630 bool isVectorInsert = isa<PackedType>(NewAI->getType()->getElementType());
Chris Lattner41b44222006-10-08 23:53:04 +0000631 const TargetData &TD = getAnalysis<TargetData>();
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000632 while (!Ptr->use_empty()) {
633 Instruction *User = cast<Instruction>(Ptr->use_back());
634
635 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
636 // The load is a bit extract from NewAI shifted right by Offset bits.
637 Value *NV = new LoadInst(NewAI, LI->getName(), LI);
Chris Lattner3323ce12006-04-14 21:42:41 +0000638 if (NV->getType() != LI->getType()) {
639 if (const PackedType *PTy = dyn_cast<PackedType>(NV->getType())) {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000640 // If the result alloca is a packed type, this is either an element
641 // access or a bitcast to another packed type.
642 if (isa<PackedType>(LI->getType())) {
643 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
Chris Lattner216c3022006-12-10 23:56:50 +0000644 } else {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000645 // Must be an element access.
646 unsigned Elt = Offset/(TD.getTypeSize(PTy->getElementType())*8);
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000647 NV = new ExtractElementInst(
648 NV, ConstantInt::get(Type::Int32Ty, Elt), "tmp", LI);
Chris Lattner216c3022006-12-10 23:56:50 +0000649 }
Chris Lattner8f7b7752006-12-15 07:32:38 +0000650 } else if (isa<PointerType>(NV->getType())) {
651 assert(isa<PointerType>(LI->getType()));
652 // Must be ptr->ptr cast. Anything else would result in NV being
653 // an integer.
654 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
655 } else {
Chris Lattner03c49532007-01-15 02:27:26 +0000656 assert(NV->getType()->isInteger() && "Unknown promotion!");
Chris Lattner8f7b7752006-12-15 07:32:38 +0000657 if (Offset && Offset < TD.getTypeSize(NV->getType())*8) {
658 NV = new ShiftInst(Instruction::LShr, NV,
Reid Spencerc635f472006-12-31 05:48:39 +0000659 ConstantInt::get(Type::Int8Ty, Offset),
Chris Lattner8f7b7752006-12-15 07:32:38 +0000660 LI->getName(), LI);
661 }
662
663 // If the result is an integer, this is a trunc or bitcast.
Chris Lattner03c49532007-01-15 02:27:26 +0000664 if (LI->getType()->isInteger()) {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000665 NV = CastInst::createTruncOrBitCast(NV, LI->getType(),
666 LI->getName(), LI);
667 } else if (LI->getType()->isFloatingPoint()) {
668 // If needed, truncate the integer to the appropriate size.
Reid Spencer8f166b02007-01-08 16:32:00 +0000669 if (NV->getType()->getPrimitiveSizeInBits() >
670 LI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000671 switch (LI->getType()->getTypeID()) {
672 default: assert(0 && "Unknown FP type!");
673 case Type::FloatTyID:
Reid Spencerc635f472006-12-31 05:48:39 +0000674 NV = new TruncInst(NV, Type::Int32Ty, LI->getName(), LI);
Chris Lattner8f7b7752006-12-15 07:32:38 +0000675 break;
676 case Type::DoubleTyID:
Reid Spencerc635f472006-12-31 05:48:39 +0000677 NV = new TruncInst(NV, Type::Int64Ty, LI->getName(), LI);
Chris Lattner8f7b7752006-12-15 07:32:38 +0000678 break;
679 }
680 }
681
682 // Then do a bitcast.
683 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
684 } else {
685 // Otherwise must be a pointer.
686 NV = new IntToPtrInst(NV, LI->getType(), LI->getName(), LI);
687 }
Chris Lattner3323ce12006-04-14 21:42:41 +0000688 }
689 }
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000690 LI->replaceAllUsesWith(NV);
691 LI->eraseFromParent();
692 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
693 assert(SI->getOperand(0) != Ptr && "Consistency error!");
694
695 // Convert the stored type to the actual type, shift it left to insert
696 // then 'or' into place.
697 Value *SV = SI->getOperand(0);
Chris Lattner3323ce12006-04-14 21:42:41 +0000698 const Type *AllocaType = NewAI->getType()->getElementType();
699 if (SV->getType() != AllocaType) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000700 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
Chris Lattner3323ce12006-04-14 21:42:41 +0000701
702 if (const PackedType *PTy = dyn_cast<PackedType>(AllocaType)) {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000703 // If the result alloca is a packed type, this is either an element
704 // access or a bitcast to another packed type.
705 if (isa<PackedType>(SV->getType())) {
706 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
707 } else {
708 // Must be an element insertion.
709 unsigned Elt = Offset/(TD.getTypeSize(PTy->getElementType())*8);
710 SV = new InsertElementInst(Old, SV,
Reid Spencerc635f472006-12-31 05:48:39 +0000711 ConstantInt::get(Type::Int32Ty, Elt),
Chris Lattner8f7b7752006-12-15 07:32:38 +0000712 "tmp", SI);
713 }
Chris Lattner3323ce12006-04-14 21:42:41 +0000714 } else {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000715 // If SV is a float, convert it to the appropriate integer type.
716 // If it is a pointer, do the same, and also handle ptr->ptr casts
717 // here.
718 switch (SV->getType()->getTypeID()) {
719 default:
720 assert(!SV->getType()->isFloatingPoint() && "Unknown FP type!");
721 break;
722 case Type::FloatTyID:
Reid Spencerc635f472006-12-31 05:48:39 +0000723 SV = new BitCastInst(SV, Type::Int32Ty, SV->getName(), SI);
Chris Lattner8f7b7752006-12-15 07:32:38 +0000724 break;
725 case Type::DoubleTyID:
Reid Spencerc635f472006-12-31 05:48:39 +0000726 SV = new BitCastInst(SV, Type::Int64Ty, SV->getName(), SI);
Chris Lattner8f7b7752006-12-15 07:32:38 +0000727 break;
728 case Type::PointerTyID:
729 if (isa<PointerType>(AllocaType))
730 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
731 else
732 SV = new PtrToIntInst(SV, TD.getIntPtrType(), SV->getName(), SI);
733 break;
734 }
735
736 unsigned SrcSize = TD.getTypeSize(SV->getType())*8;
737
738 // Always zero extend the value if needed.
739 if (SV->getType() != AllocaType)
740 SV = CastInst::createZExtOrBitCast(SV, AllocaType,
741 SV->getName(), SI);
742 if (Offset && Offset < AllocaType->getPrimitiveSizeInBits())
Chris Lattner3323ce12006-04-14 21:42:41 +0000743 SV = new ShiftInst(Instruction::Shl, SV,
Reid Spencerc635f472006-12-31 05:48:39 +0000744 ConstantInt::get(Type::Int8Ty, Offset),
Chris Lattner3323ce12006-04-14 21:42:41 +0000745 SV->getName()+".adj", SI);
746 // Mask out the bits we are about to insert from the old value.
Chris Lattner41b44222006-10-08 23:53:04 +0000747 unsigned TotalBits = TD.getTypeSize(SV->getType())*8;
Chris Lattner8f7b7752006-12-15 07:32:38 +0000748 if (TotalBits != SrcSize) {
749 assert(TotalBits > SrcSize);
750 uint64_t Mask = ~(((1ULL << SrcSize)-1) << Offset);
Chris Lattner03c49532007-01-15 02:27:26 +0000751 Mask = Mask & SV->getType()->getIntegerTypeMask();
Chris Lattner3323ce12006-04-14 21:42:41 +0000752 Old = BinaryOperator::createAnd(Old,
Reid Spencere0fc4df2006-10-20 07:07:24 +0000753 ConstantInt::get(Old->getType(), Mask),
Chris Lattner3323ce12006-04-14 21:42:41 +0000754 Old->getName()+".mask", SI);
755 SV = BinaryOperator::createOr(Old, SV, SV->getName()+".ins", SI);
756 }
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000757 }
758 }
759 new StoreInst(SV, NewAI, SI);
760 SI->eraseFromParent();
761
762 } else if (CastInst *CI = dyn_cast<CastInst>(User)) {
763 unsigned NewOff = Offset;
764 const TargetData &TD = getAnalysis<TargetData>();
Chris Lattner3323ce12006-04-14 21:42:41 +0000765 if (TD.isBigEndian() && !isVectorInsert) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000766 // Adjust the pointer. For example, storing 16-bits into a 32-bit
767 // alloca with just a cast makes it modify the top 16-bits.
768 const Type *SrcTy = cast<PointerType>(Ptr->getType())->getElementType();
769 const Type *DstTy = cast<PointerType>(CI->getType())->getElementType();
770 int PtrDiffBits = TD.getTypeSize(SrcTy)*8-TD.getTypeSize(DstTy)*8;
771 NewOff += PtrDiffBits;
772 }
773 ConvertUsesToScalar(CI, NewAI, NewOff);
774 CI->eraseFromParent();
775 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
776 const PointerType *AggPtrTy =
777 cast<PointerType>(GEP->getOperand(0)->getType());
778 const TargetData &TD = getAnalysis<TargetData>();
779 unsigned AggSizeInBits = TD.getTypeSize(AggPtrTy->getElementType())*8;
780
781 // Check to see if this is stepping over an element: GEP Ptr, int C
782 unsigned NewOffset = Offset;
783 if (GEP->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000784 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000785 unsigned BitOffset = Idx*AggSizeInBits;
786
Chris Lattner3323ce12006-04-14 21:42:41 +0000787 if (TD.isLittleEndian() || isVectorInsert)
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000788 NewOffset += BitOffset;
789 else
790 NewOffset -= BitOffset;
791
792 } else if (GEP->getNumOperands() == 3) {
793 // We know that operand #2 is zero.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000794 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000795 const Type *AggTy = AggPtrTy->getElementType();
796 if (const SequentialType *SeqTy = dyn_cast<SequentialType>(AggTy)) {
797 unsigned ElSizeBits = TD.getTypeSize(SeqTy->getElementType())*8;
798
Chris Lattner3323ce12006-04-14 21:42:41 +0000799 if (TD.isLittleEndian() || isVectorInsert)
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000800 NewOffset += ElSizeBits*Idx;
801 else
802 NewOffset += AggSizeInBits-ElSizeBits*(Idx+1);
803 } else if (const StructType *STy = dyn_cast<StructType>(AggTy)) {
804 unsigned EltBitOffset = TD.getStructLayout(STy)->MemberOffsets[Idx]*8;
805
Chris Lattner3323ce12006-04-14 21:42:41 +0000806 if (TD.isLittleEndian() || isVectorInsert)
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000807 NewOffset += EltBitOffset;
808 else {
809 const PointerType *ElPtrTy = cast<PointerType>(GEP->getType());
810 unsigned ElSizeBits = TD.getTypeSize(ElPtrTy->getElementType())*8;
811 NewOffset += AggSizeInBits-(EltBitOffset+ElSizeBits);
812 }
813
814 } else {
815 assert(0 && "Unsupported operation!");
816 abort();
817 }
818 } else {
819 assert(0 && "Unsupported operation!");
820 abort();
821 }
822 ConvertUsesToScalar(GEP, NewAI, NewOffset);
823 GEP->eraseFromParent();
824 } else {
825 assert(0 && "Unsupported operation!");
826 abort();
827 }
828 }
829}