blob: 3955cb8dbb10ef3ef2653ecb82c98a329422f2af [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
22#include "llvm/Transforms/Scalar.h"
Chris Lattner5d8a12e2003-09-11 16:45:55 +000023#include "llvm/Constants.h"
24#include "llvm/DerivedTypes.h"
Chris Lattnerfb41a502003-05-27 15:45:27 +000025#include "llvm/Function.h"
26#include "llvm/Pass.h"
Misha Brukman2b3387a2004-07-29 17:05:13 +000027#include "llvm/Instructions.h"
Chris Lattner5d8a12e2003-09-11 16:45:55 +000028#include "llvm/Analysis/Dominators.h"
29#include "llvm/Target/TargetData.h"
30#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Chris Lattner996795b2006-06-28 23:17:24 +000031#include "llvm/Support/Debug.h"
Chris Lattner3b0a62d2005-12-12 07:19:13 +000032#include "llvm/Support/GetElementPtrTypeIterator.h"
33#include "llvm/Support/MathExtras.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000034#include "llvm/Support/Compiler.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000035#include "llvm/ADT/Statistic.h"
36#include "llvm/ADT/StringExtras.h"
Chris Lattnerc597b8a2006-01-22 23:32:06 +000037#include <iostream>
Chris Lattner40d2aeb2003-12-02 17:43:55 +000038using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000039
Chris Lattnerfb41a502003-05-27 15:45:27 +000040namespace {
Misha Brukman217ca0b2003-09-11 16:58:31 +000041 Statistic<> NumReplaced("scalarrepl", "Number of allocas broken up");
42 Statistic<> NumPromoted("scalarrepl", "Number of allocas promoted");
Chris Lattner3b0a62d2005-12-12 07:19:13 +000043 Statistic<> NumConverted("scalarrepl",
44 "Number of aggregates converted to scalar");
Chris Lattnerfb41a502003-05-27 15:45:27 +000045
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
143 // If we can turn this aggregate value (potentially with casts) into a
144 // simple scalar value that can be mem2reg'd into a register value.
145 bool IsNotTrivial = false;
146 if (const Type *ActualType = CanConvertToScalar(AI, IsNotTrivial))
Chris Lattnerdae49df2006-04-20 20:48:50 +0000147 if (IsNotTrivial && ActualType != Type::VoidTy) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000148 ConvertToScalar(AI, ActualType);
149 Changed = true;
150 continue;
151 }
Chris Lattnerfb41a502003-05-27 15:45:27 +0000152
153 // We cannot transform the allocation instruction if it is an array
Chris Lattnerc16b2102003-05-27 16:09:27 +0000154 // allocation (allocations OF arrays are ok though), and an allocation of a
155 // scalar value cannot be decomposed at all.
156 //
Chris Lattnerfb41a502003-05-27 15:45:27 +0000157 if (AI->isArrayAllocation() ||
Chris Lattnerc16b2102003-05-27 16:09:27 +0000158 (!isa<StructType>(AI->getAllocatedType()) &&
159 !isa<ArrayType>(AI->getAllocatedType()))) continue;
160
Chris Lattner6e5398d2003-05-30 04:15:41 +0000161 // Check that all of the users of the allocation are capable of being
162 // transformed.
Chris Lattner88819122004-11-14 04:24:28 +0000163 switch (isSafeAllocaToScalarRepl(AI)) {
164 default: assert(0 && "Unexpected value!");
165 case 0: // Not safe to scalar replace.
Chris Lattner6e5398d2003-05-30 04:15:41 +0000166 continue;
Chris Lattner88819122004-11-14 04:24:28 +0000167 case 1: // Safe, but requires cleanup/canonicalizations first
168 CanonicalizeAllocaUsers(AI);
169 case 3: // Safe to scalar replace.
170 break;
171 }
Chris Lattnerfb41a502003-05-27 15:45:27 +0000172
173 DEBUG(std::cerr << "Found inst to xform: " << *AI);
174 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000175
Chris Lattnerfb41a502003-05-27 15:45:27 +0000176 std::vector<AllocaInst*> ElementAllocas;
177 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
178 ElementAllocas.reserve(ST->getNumContainedTypes());
179 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Nate Begeman848622f2005-11-05 09:21:28 +0000180 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
181 AI->getAlignment(),
Chris Lattnerfb41a502003-05-27 15:45:27 +0000182 AI->getName() + "." + utostr(i), AI);
183 ElementAllocas.push_back(NA);
184 WorkList.push_back(NA); // Add to worklist for recursive processing
185 }
186 } else {
Chris Lattner6e5398d2003-05-30 04:15:41 +0000187 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
Chris Lattnerfb41a502003-05-27 15:45:27 +0000188 ElementAllocas.reserve(AT->getNumElements());
189 const Type *ElTy = AT->getElementType();
190 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Nate Begeman848622f2005-11-05 09:21:28 +0000191 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Chris Lattnerfb41a502003-05-27 15:45:27 +0000192 AI->getName() + "." + utostr(i), AI);
193 ElementAllocas.push_back(NA);
194 WorkList.push_back(NA); // Add to worklist for recursive processing
195 }
196 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000197
Chris Lattnerfb41a502003-05-27 15:45:27 +0000198 // Now that we have created the alloca instructions that we want to use,
199 // expand the getelementptr instructions to use them.
200 //
Chris Lattnerb5f8eb82004-06-19 02:02:22 +0000201 while (!AI->use_empty()) {
202 Instruction *User = cast<Instruction>(AI->use_back());
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000203 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
204 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
Misha Brukmanb1c93172005-04-21 23:48:37 +0000205 unsigned Idx =
Chris Lattnerce274ce2005-01-08 19:34:41 +0000206 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000207
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000208 assert(Idx < ElementAllocas.size() && "Index out of range?");
209 AllocaInst *AllocaToUse = ElementAllocas[Idx];
Misha Brukmanb1c93172005-04-21 23:48:37 +0000210
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000211 Value *RepValue;
212 if (GEPI->getNumOperands() == 3) {
213 // Do not insert a new getelementptr instruction with zero indices, only
214 // to have it optimized out later.
215 RepValue = AllocaToUse;
Chris Lattnerfb41a502003-05-27 15:45:27 +0000216 } else {
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000217 // We are indexing deeply into the structure, so we still need a
218 // getelement ptr instruction to finish the indexing. This may be
219 // expanded itself once the worklist is rerun.
220 //
221 std::string OldName = GEPI->getName(); // Steal the old name.
222 std::vector<Value*> NewArgs;
223 NewArgs.push_back(Constant::getNullValue(Type::IntTy));
224 NewArgs.insert(NewArgs.end(), GEPI->op_begin()+3, GEPI->op_end());
225 GEPI->setName("");
226 RepValue = new GetElementPtrInst(AllocaToUse, NewArgs, OldName, GEPI);
Chris Lattnerfb41a502003-05-27 15:45:27 +0000227 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000228
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000229 // Move all of the users over to the new GEP.
230 GEPI->replaceAllUsesWith(RepValue);
231 // Delete the old GEP
232 GEPI->eraseFromParent();
Chris Lattnerfb41a502003-05-27 15:45:27 +0000233 }
234
235 // Finally, delete the Alloca instruction
236 AI->getParent()->getInstList().erase(AI);
Chris Lattnerc16b2102003-05-27 16:09:27 +0000237 NumReplaced++;
Chris Lattnerfb41a502003-05-27 15:45:27 +0000238 }
239
240 return Changed;
241}
Chris Lattner6e5398d2003-05-30 04:15:41 +0000242
243
Chris Lattner88819122004-11-14 04:24:28 +0000244/// isSafeElementUse - Check to see if this use is an allowed use for a
245/// getelementptr instruction of an array aggregate allocation.
246///
247int SROA::isSafeElementUse(Value *Ptr) {
248 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
249 I != E; ++I) {
250 Instruction *User = cast<Instruction>(*I);
251 switch (User->getOpcode()) {
252 case Instruction::Load: break;
253 case Instruction::Store:
254 // Store is ok if storing INTO the pointer, not storing the pointer
255 if (User->getOperand(0) == Ptr) return 0;
256 break;
257 case Instruction::GetElementPtr: {
258 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
259 if (GEP->getNumOperands() > 1) {
260 if (!isa<Constant>(GEP->getOperand(1)) ||
261 !cast<Constant>(GEP->getOperand(1))->isNullValue())
262 return 0; // Using pointer arithmetic to navigate the array...
263 }
264 if (!isSafeElementUse(GEP)) return 0;
265 break;
266 }
267 default:
268 DEBUG(std::cerr << " Transformation preventing inst: " << *User);
269 return 0;
270 }
271 }
272 return 3; // All users look ok :)
273}
274
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000275/// AllUsersAreLoads - Return true if all users of this value are loads.
276static bool AllUsersAreLoads(Value *Ptr) {
277 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
278 I != E; ++I)
279 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
280 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000281 return true;
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000282}
283
Chris Lattner6e5398d2003-05-30 04:15:41 +0000284/// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
285/// aggregate allocation.
286///
Chris Lattner88819122004-11-14 04:24:28 +0000287int SROA::isSafeUseOfAllocation(Instruction *User) {
288 if (!isa<GetElementPtrInst>(User)) return 0;
Chris Lattner52310702003-11-25 21:09:18 +0000289
290 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
291 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
292
Chris Lattnerfc34f8b2006-03-08 01:05:29 +0000293 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
Chris Lattner52310702003-11-25 21:09:18 +0000294 if (I == E ||
295 I.getOperand() != Constant::getNullValue(I.getOperand()->getType()))
Chris Lattner88819122004-11-14 04:24:28 +0000296 return 0;
Chris Lattner52310702003-11-25 21:09:18 +0000297
298 ++I;
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000299 if (I == E) return 0; // ran out of GEP indices??
Chris Lattner52310702003-11-25 21:09:18 +0000300
301 // If this is a use of an array allocation, do a bit more checking for sanity.
302 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
303 uint64_t NumElements = AT->getNumElements();
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000304
305 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
306 // Check to make sure that index falls within the array. If not,
307 // something funny is going on, so we won't do the optimization.
308 //
309 if (cast<ConstantInt>(GEPI->getOperand(2))->getRawValue() >= NumElements)
310 return 0;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000311
Chris Lattnerfc34f8b2006-03-08 01:05:29 +0000312 // We cannot scalar repl this level of the array unless any array
313 // sub-indices are in-range constants. In particular, consider:
314 // A[0][i]. We cannot know that the user isn't doing invalid things like
315 // allowing i to index an out-of-range subscript that accesses A[1].
316 //
317 // Scalar replacing *just* the outer index of the array is probably not
318 // going to be a win anyway, so just give up.
319 for (++I; I != E && isa<ArrayType>(*I); ++I) {
320 const ArrayType *SubArrayTy = cast<ArrayType>(*I);
321 uint64_t NumElements = SubArrayTy->getNumElements();
322 if (!isa<ConstantInt>(I.getOperand())) return 0;
323 if (cast<ConstantInt>(I.getOperand())->getRawValue() >= NumElements)
324 return 0;
325 }
326
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000327 } else {
328 // If this is an array index and the index is not constant, we cannot
329 // promote... that is unless the array has exactly one or two elements in
330 // it, in which case we CAN promote it, but we have to canonicalize this
331 // out if this is the only problem.
Chris Lattnerfc34f8b2006-03-08 01:05:29 +0000332 if ((NumElements == 1 || NumElements == 2) &&
333 AllUsersAreLoads(GEPI))
334 return 1; // Canonicalization required!
Chris Lattner88819122004-11-14 04:24:28 +0000335 return 0;
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000336 }
Chris Lattner6e5398d2003-05-30 04:15:41 +0000337 }
Chris Lattner52310702003-11-25 21:09:18 +0000338
339 // If there are any non-simple uses of this getelementptr, make sure to reject
340 // them.
341 return isSafeElementUse(GEPI);
Chris Lattner6e5398d2003-05-30 04:15:41 +0000342}
343
Chris Lattner88819122004-11-14 04:24:28 +0000344/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
345/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
346/// or 1 if safe after canonicalization has been performed.
Chris Lattner6e5398d2003-05-30 04:15:41 +0000347///
Chris Lattner88819122004-11-14 04:24:28 +0000348int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
Chris Lattner6e5398d2003-05-30 04:15:41 +0000349 // Loop over the use list of the alloca. We can only transform it if all of
350 // the users are safe to transform.
351 //
Chris Lattner88819122004-11-14 04:24:28 +0000352 int isSafe = 3;
Chris Lattner6e5398d2003-05-30 04:15:41 +0000353 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
Chris Lattner88819122004-11-14 04:24:28 +0000354 I != E; ++I) {
355 isSafe &= isSafeUseOfAllocation(cast<Instruction>(*I));
356 if (isSafe == 0) {
Chris Lattner6e5398d2003-05-30 04:15:41 +0000357 DEBUG(std::cerr << "Cannot transform: " << *AI << " due to user: "
Chris Lattner88819122004-11-14 04:24:28 +0000358 << **I);
359 return 0;
Chris Lattner6e5398d2003-05-30 04:15:41 +0000360 }
Chris Lattner88819122004-11-14 04:24:28 +0000361 }
362 // If we require cleanup, isSafe is now 1, otherwise it is 3.
363 return isSafe;
364}
365
366/// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified
367/// allocation, but only if cleaned up, perform the cleanups required.
368void SROA::CanonicalizeAllocaUsers(AllocationInst *AI) {
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000369 // At this point, we know that the end result will be SROA'd and promoted, so
370 // we can insert ugly code if required so long as sroa+mem2reg will clean it
371 // up.
372 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
373 UI != E; ) {
374 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(*UI++);
Reid Spencer93396382004-11-15 17:29:41 +0000375 gep_type_iterator I = gep_type_begin(GEPI);
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000376 ++I;
Chris Lattner88819122004-11-14 04:24:28 +0000377
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000378 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
379 uint64_t NumElements = AT->getNumElements();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000380
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000381 if (!isa<ConstantInt>(I.getOperand())) {
382 if (NumElements == 1) {
383 GEPI->setOperand(2, Constant::getNullValue(Type::IntTy));
384 } else {
385 assert(NumElements == 2 && "Unhandled case!");
386 // All users of the GEP must be loads. At each use of the GEP, insert
387 // two loads of the appropriate indexed GEP and select between them.
388 Value *IsOne = BinaryOperator::createSetNE(I.getOperand(),
389 Constant::getNullValue(I.getOperand()->getType()),
390 "isone", GEPI);
391 // Insert the new GEP instructions, which are properly indexed.
392 std::vector<Value*> Indices(GEPI->op_begin()+1, GEPI->op_end());
393 Indices[1] = Constant::getNullValue(Type::IntTy);
394 Value *ZeroIdx = new GetElementPtrInst(GEPI->getOperand(0), Indices,
395 GEPI->getName()+".0", GEPI);
396 Indices[1] = ConstantInt::get(Type::IntTy, 1);
397 Value *OneIdx = new GetElementPtrInst(GEPI->getOperand(0), Indices,
398 GEPI->getName()+".1", GEPI);
399 // Replace all loads of the variable index GEP with loads from both
400 // indexes and a select.
401 while (!GEPI->use_empty()) {
402 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
403 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
404 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
405 Value *R = new SelectInst(IsOne, One, Zero, LI->getName(), LI);
406 LI->replaceAllUsesWith(R);
407 LI->eraseFromParent();
408 }
409 GEPI->eraseFromParent();
410 }
411 }
412 }
413 }
Chris Lattner6e5398d2003-05-30 04:15:41 +0000414}
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000415
416/// MergeInType - Add the 'In' type to the accumulated type so far. If the
417/// types are incompatible, return true, otherwise update Accum and return
418/// false.
Chris Lattner3323ce12006-04-14 21:42:41 +0000419///
420/// There are two cases we handle here:
421/// 1) An effectively integer union, where the pieces are stored into as
422/// smaller integers (common with byte swap and other idioms).
423/// 2) A union of a vector and its elements. Here we turn element accesses
424/// into insert/extract element operations.
Chris Lattner05f82722006-10-08 23:28:04 +0000425static bool MergeInType(const Type *In, const Type *&Accum,
426 const TargetData &TD) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000427 // If this is our first type, just use it.
Chris Lattner3323ce12006-04-14 21:42:41 +0000428 const PackedType *PTy;
429 if (Accum == Type::VoidTy || In == Accum) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000430 Accum = In;
Chris Lattner3323ce12006-04-14 21:42:41 +0000431 } else if (In->isIntegral() && Accum->isIntegral()) { // integer union.
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000432 // Otherwise pick whichever type is larger.
433 if (In->getTypeID() > Accum->getTypeID())
434 Accum = In;
Chris Lattner05f82722006-10-08 23:28:04 +0000435 } else if (isa<PointerType>(In) && isa<PointerType>(Accum)) {
436 // Pointer unions just stay as a pointer.
437 // Nothing.
Chris Lattner3323ce12006-04-14 21:42:41 +0000438 } else if ((PTy = dyn_cast<PackedType>(Accum)) &&
439 PTy->getElementType() == In) {
440 // Accum is a vector, and we are accessing an element: ok.
441 } else if ((PTy = dyn_cast<PackedType>(In)) &&
442 PTy->getElementType() == Accum) {
443 // In is a vector, and accum is an element: ok, remember In.
444 Accum = In;
445 } else {
446 return true;
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000447 }
448 return false;
449}
450
451/// getUIntAtLeastAsBitAs - Return an unsigned integer type that is at least
452/// as big as the specified type. If there is no suitable type, this returns
453/// null.
454const Type *getUIntAtLeastAsBitAs(unsigned NumBits) {
455 if (NumBits > 64) return 0;
456 if (NumBits > 32) return Type::ULongTy;
457 if (NumBits > 16) return Type::UIntTy;
458 if (NumBits > 8) return Type::UShortTy;
459 return Type::UByteTy;
460}
461
462/// CanConvertToScalar - V is a pointer. If we can convert the pointee to a
463/// single scalar integer type, return that type. Further, if the use is not
464/// a completely trivial use that mem2reg could promote, set IsNotTrivial. If
465/// there are no uses of this pointer, return Type::VoidTy to differentiate from
466/// failure.
467///
468const Type *SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial) {
469 const Type *UsedType = Type::VoidTy; // No uses, no forced type.
470 const TargetData &TD = getAnalysis<TargetData>();
471 const PointerType *PTy = cast<PointerType>(V->getType());
472
473 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
474 Instruction *User = cast<Instruction>(*UI);
475
476 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner05f82722006-10-08 23:28:04 +0000477 if (MergeInType(LI->getType(), UsedType, TD))
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000478 return 0;
479
480 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
481 // Storing the pointer, not the into the value?
482 if (SI->getOperand(0) == V) return 0;
483
Chris Lattner3323ce12006-04-14 21:42:41 +0000484 // NOTE: We could handle storing of FP imms into integers here!
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000485
Chris Lattner05f82722006-10-08 23:28:04 +0000486 if (MergeInType(SI->getOperand(0)->getType(), UsedType, TD))
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000487 return 0;
488 } else if (CastInst *CI = dyn_cast<CastInst>(User)) {
489 if (!isa<PointerType>(CI->getType())) return 0;
490 IsNotTrivial = true;
491 const Type *SubTy = CanConvertToScalar(CI, IsNotTrivial);
Chris Lattner05f82722006-10-08 23:28:04 +0000492 if (!SubTy || MergeInType(SubTy, UsedType, TD)) return 0;
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000493 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
494 // Check to see if this is stepping over an element: GEP Ptr, int C
495 if (GEP->getNumOperands() == 2 && isa<ConstantInt>(GEP->getOperand(1))) {
496 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getRawValue();
497 unsigned ElSize = TD.getTypeSize(PTy->getElementType());
498 unsigned BitOffset = Idx*ElSize*8;
499 if (BitOffset > 64 || !isPowerOf2_32(ElSize)) return 0;
500
501 IsNotTrivial = true;
502 const Type *SubElt = CanConvertToScalar(GEP, IsNotTrivial);
503 if (SubElt == 0) return 0;
Chris Lattner3323ce12006-04-14 21:42:41 +0000504 if (SubElt != Type::VoidTy && SubElt->isInteger()) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000505 const Type *NewTy =
506 getUIntAtLeastAsBitAs(SubElt->getPrimitiveSizeInBits()+BitOffset);
Chris Lattner05f82722006-10-08 23:28:04 +0000507 if (NewTy == 0 || MergeInType(NewTy, UsedType, TD)) return 0;
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000508 continue;
509 }
510 } else if (GEP->getNumOperands() == 3 &&
511 isa<ConstantInt>(GEP->getOperand(1)) &&
512 isa<ConstantInt>(GEP->getOperand(2)) &&
513 cast<Constant>(GEP->getOperand(1))->isNullValue()) {
514 // We are stepping into an element, e.g. a structure or an array:
515 // GEP Ptr, int 0, uint C
516 const Type *AggTy = PTy->getElementType();
517 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getRawValue();
518
519 if (const ArrayType *ATy = dyn_cast<ArrayType>(AggTy)) {
520 if (Idx >= ATy->getNumElements()) return 0; // Out of range.
Chris Lattner3323ce12006-04-14 21:42:41 +0000521 } else if (const PackedType *PackedTy = dyn_cast<PackedType>(AggTy)) {
522 // Getting an element of the packed vector.
523 if (Idx >= PackedTy->getNumElements()) return 0; // Out of range.
524
525 // Merge in the packed type.
Chris Lattner05f82722006-10-08 23:28:04 +0000526 if (MergeInType(PackedTy, UsedType, TD)) return 0;
Chris Lattner3323ce12006-04-14 21:42:41 +0000527
528 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
529 if (SubTy == 0) return 0;
530
Chris Lattner05f82722006-10-08 23:28:04 +0000531 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
Chris Lattner3323ce12006-04-14 21:42:41 +0000532 return 0;
533
534 // We'll need to change this to an insert/extract element operation.
535 IsNotTrivial = true;
536 continue; // Everything looks ok
537
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000538 } else if (isa<StructType>(AggTy)) {
539 // Structs are always ok.
540 } else {
541 return 0;
542 }
543 const Type *NTy = getUIntAtLeastAsBitAs(TD.getTypeSize(AggTy)*8);
Chris Lattner05f82722006-10-08 23:28:04 +0000544 if (NTy == 0 || MergeInType(NTy, UsedType, TD)) return 0;
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000545 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
546 if (SubTy == 0) return 0;
Chris Lattner05f82722006-10-08 23:28:04 +0000547 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000548 return 0;
549 continue; // Everything looks ok
550 }
551 return 0;
552 } else {
553 // Cannot handle this!
554 return 0;
555 }
556 }
557
558 return UsedType;
559}
560
561/// ConvertToScalar - The specified alloca passes the CanConvertToScalar
562/// predicate and is non-trivial. Convert it to something that can be trivially
563/// promoted into a register by mem2reg.
564void SROA::ConvertToScalar(AllocationInst *AI, const Type *ActualTy) {
565 DEBUG(std::cerr << "CONVERT TO SCALAR: " << *AI << " TYPE = "
566 << *ActualTy << "\n");
567 ++NumConverted;
568
569 BasicBlock *EntryBlock = AI->getParent();
570 assert(EntryBlock == &EntryBlock->getParent()->front() &&
571 "Not in the entry block!");
572 EntryBlock->getInstList().remove(AI); // Take the alloca out of the program.
573
Chris Lattner3323ce12006-04-14 21:42:41 +0000574 if (ActualTy->isInteger())
575 ActualTy = ActualTy->getUnsignedVersion();
576
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000577 // Create and insert the alloca.
Chris Lattner3323ce12006-04-14 21:42:41 +0000578 AllocaInst *NewAI = new AllocaInst(ActualTy, 0, AI->getName(),
579 EntryBlock->begin());
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000580 ConvertUsesToScalar(AI, NewAI, 0);
581 delete AI;
582}
583
584
585/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
Chris Lattner3323ce12006-04-14 21:42:41 +0000586/// directly. This happens when we are converting an "integer union" to a
587/// single integer scalar, or when we are converting a "vector union" to a
588/// vector with insert/extractelement instructions.
589///
590/// Offset is an offset from the original alloca, in bits that need to be
591/// shifted to the right. By the end of this, there should be no uses of Ptr.
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000592void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset) {
Chris Lattner3323ce12006-04-14 21:42:41 +0000593 bool isVectorInsert = isa<PackedType>(NewAI->getType()->getElementType());
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000594 while (!Ptr->use_empty()) {
595 Instruction *User = cast<Instruction>(Ptr->use_back());
596
597 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
598 // The load is a bit extract from NewAI shifted right by Offset bits.
599 Value *NV = new LoadInst(NewAI, LI->getName(), LI);
Chris Lattner3323ce12006-04-14 21:42:41 +0000600 if (NV->getType() != LI->getType()) {
601 if (const PackedType *PTy = dyn_cast<PackedType>(NV->getType())) {
602 // Must be an element access.
603 unsigned Elt = Offset/PTy->getElementType()->getPrimitiveSizeInBits();
604 NV = new ExtractElementInst(NV, ConstantUInt::get(Type::UIntTy, Elt),
605 "tmp", LI);
606 } else {
607 assert(NV->getType()->isInteger() && "Unknown promotion!");
608 if (Offset && Offset < NV->getType()->getPrimitiveSizeInBits())
609 NV = new ShiftInst(Instruction::Shr, NV,
610 ConstantUInt::get(Type::UByteTy, Offset),
611 LI->getName(), LI);
612 NV = new CastInst(NV, LI->getType(), LI->getName(), LI);
613 }
614 }
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000615 LI->replaceAllUsesWith(NV);
616 LI->eraseFromParent();
617 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
618 assert(SI->getOperand(0) != Ptr && "Consistency error!");
619
620 // Convert the stored type to the actual type, shift it left to insert
621 // then 'or' into place.
622 Value *SV = SI->getOperand(0);
Chris Lattner3323ce12006-04-14 21:42:41 +0000623 const Type *AllocaType = NewAI->getType()->getElementType();
624 if (SV->getType() != AllocaType) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000625 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
Chris Lattner3323ce12006-04-14 21:42:41 +0000626
627 if (const PackedType *PTy = dyn_cast<PackedType>(AllocaType)) {
628 // Must be an element insertion.
629 unsigned Elt = Offset/PTy->getElementType()->getPrimitiveSizeInBits();
630 SV = new InsertElementInst(Old, SV,
631 ConstantUInt::get(Type::UIntTy, Elt),
632 "tmp", SI);
633 } else {
634 // If SV is signed, convert it to unsigned, so that the next cast zero
635 // extends the value.
636 if (SV->getType()->isSigned())
637 SV = new CastInst(SV, SV->getType()->getUnsignedVersion(),
638 SV->getName(), SI);
639 SV = new CastInst(SV, Old->getType(), SV->getName(), SI);
640 if (Offset && Offset < SV->getType()->getPrimitiveSizeInBits())
641 SV = new ShiftInst(Instruction::Shl, SV,
642 ConstantUInt::get(Type::UByteTy, Offset),
643 SV->getName()+".adj", SI);
644 // Mask out the bits we are about to insert from the old value.
645 unsigned TotalBits = SV->getType()->getPrimitiveSizeInBits();
646 unsigned InsertBits =
647 SI->getOperand(0)->getType()->getPrimitiveSizeInBits();
648 if (TotalBits != InsertBits) {
649 assert(TotalBits > InsertBits);
650 uint64_t Mask = ~(((1ULL << InsertBits)-1) << Offset);
651 if (TotalBits != 64)
652 Mask = Mask & ((1ULL << TotalBits)-1);
653 Old = BinaryOperator::createAnd(Old,
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000654 ConstantUInt::get(Old->getType(), Mask),
Chris Lattner3323ce12006-04-14 21:42:41 +0000655 Old->getName()+".mask", SI);
656 SV = BinaryOperator::createOr(Old, SV, SV->getName()+".ins", SI);
657 }
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000658 }
659 }
660 new StoreInst(SV, NewAI, SI);
661 SI->eraseFromParent();
662
663 } else if (CastInst *CI = dyn_cast<CastInst>(User)) {
664 unsigned NewOff = Offset;
665 const TargetData &TD = getAnalysis<TargetData>();
Chris Lattner3323ce12006-04-14 21:42:41 +0000666 if (TD.isBigEndian() && !isVectorInsert) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000667 // Adjust the pointer. For example, storing 16-bits into a 32-bit
668 // alloca with just a cast makes it modify the top 16-bits.
669 const Type *SrcTy = cast<PointerType>(Ptr->getType())->getElementType();
670 const Type *DstTy = cast<PointerType>(CI->getType())->getElementType();
671 int PtrDiffBits = TD.getTypeSize(SrcTy)*8-TD.getTypeSize(DstTy)*8;
672 NewOff += PtrDiffBits;
673 }
674 ConvertUsesToScalar(CI, NewAI, NewOff);
675 CI->eraseFromParent();
676 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
677 const PointerType *AggPtrTy =
678 cast<PointerType>(GEP->getOperand(0)->getType());
679 const TargetData &TD = getAnalysis<TargetData>();
680 unsigned AggSizeInBits = TD.getTypeSize(AggPtrTy->getElementType())*8;
681
682 // Check to see if this is stepping over an element: GEP Ptr, int C
683 unsigned NewOffset = Offset;
684 if (GEP->getNumOperands() == 2) {
685 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getRawValue();
686 unsigned BitOffset = Idx*AggSizeInBits;
687
Chris Lattner3323ce12006-04-14 21:42:41 +0000688 if (TD.isLittleEndian() || isVectorInsert)
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000689 NewOffset += BitOffset;
690 else
691 NewOffset -= BitOffset;
692
693 } else if (GEP->getNumOperands() == 3) {
694 // We know that operand #2 is zero.
695 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getRawValue();
696 const Type *AggTy = AggPtrTy->getElementType();
697 if (const SequentialType *SeqTy = dyn_cast<SequentialType>(AggTy)) {
698 unsigned ElSizeBits = TD.getTypeSize(SeqTy->getElementType())*8;
699
Chris Lattner3323ce12006-04-14 21:42:41 +0000700 if (TD.isLittleEndian() || isVectorInsert)
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000701 NewOffset += ElSizeBits*Idx;
702 else
703 NewOffset += AggSizeInBits-ElSizeBits*(Idx+1);
704 } else if (const StructType *STy = dyn_cast<StructType>(AggTy)) {
705 unsigned EltBitOffset = TD.getStructLayout(STy)->MemberOffsets[Idx]*8;
706
Chris Lattner3323ce12006-04-14 21:42:41 +0000707 if (TD.isLittleEndian() || isVectorInsert)
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000708 NewOffset += EltBitOffset;
709 else {
710 const PointerType *ElPtrTy = cast<PointerType>(GEP->getType());
711 unsigned ElSizeBits = TD.getTypeSize(ElPtrTy->getElementType())*8;
712 NewOffset += AggSizeInBits-(EltBitOffset+ElSizeBits);
713 }
714
715 } else {
716 assert(0 && "Unsupported operation!");
717 abort();
718 }
719 } else {
720 assert(0 && "Unsupported operation!");
721 abort();
722 }
723 ConvertUsesToScalar(GEP, NewAI, NewOffset);
724 GEP->eraseFromParent();
725 } else {
726 assert(0 && "Unsupported operation!");
727 abort();
728 }
729 }
730}