blob: 5bbb5aef03f0ccfccf741d3db0ed0079db7a3901 [file] [log] [blame]
Chris Lattnerfb41a502003-05-27 15:45:27 +00001//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerfb41a502003-05-27 15:45:27 +00009//
10// This transformation implements the well known scalar replacement of
11// aggregates transformation. This xform breaks up alloca instructions of
12// aggregate type (structure or array) into individual alloca instructions for
Chris Lattner5d8a12e2003-09-11 16:45:55 +000013// each member (if possible). Then, if possible, it transforms the individual
14// alloca instructions into nice clean scalar SSA form.
15//
16// This combines a simple SRoA algorithm with the Mem2Reg algorithm because
17// often interact, especially for C++ programs. As such, iterating between
18// SRoA, then Mem2Reg until we run out of things to promote works well.
Chris Lattnerfb41a502003-05-27 15:45:27 +000019//
20//===----------------------------------------------------------------------===//
21
Chris Lattner79a42ac2006-12-19 21:40:18 +000022#define DEBUG_TYPE "scalarrepl"
Chris Lattnerfb41a502003-05-27 15:45:27 +000023#include "llvm/Transforms/Scalar.h"
Chris Lattner5d8a12e2003-09-11 16:45:55 +000024#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
Chris Lattnerfb41a502003-05-27 15:45:27 +000026#include "llvm/Function.h"
Misha Brukman2b3387a2004-07-29 17:05:13 +000027#include "llvm/Instructions.h"
Chris Lattner66e6a822007-03-05 07:52:57 +000028#include "llvm/IntrinsicInst.h"
29#include "llvm/Pass.h"
Chris Lattner5d8a12e2003-09-11 16:45:55 +000030#include "llvm/Analysis/Dominators.h"
31#include "llvm/Target/TargetData.h"
32#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Chris Lattner996795b2006-06-28 23:17:24 +000033#include "llvm/Support/Debug.h"
Chris Lattner3b0a62d2005-12-12 07:19:13 +000034#include "llvm/Support/GetElementPtrTypeIterator.h"
35#include "llvm/Support/MathExtras.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000036#include "llvm/Support/Compiler.h"
Chris Lattnera7315132007-02-12 22:56:41 +000037#include "llvm/ADT/SmallVector.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000038#include "llvm/ADT/Statistic.h"
39#include "llvm/ADT/StringExtras.h"
Chris Lattner40d2aeb2003-12-02 17:43:55 +000040using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000041
Chris Lattner79a42ac2006-12-19 21:40:18 +000042STATISTIC(NumReplaced, "Number of allocas broken up");
43STATISTIC(NumPromoted, "Number of allocas promoted");
44STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattnerfb41a502003-05-27 15:45:27 +000045
Chris Lattner79a42ac2006-12-19 21:40:18 +000046namespace {
Chris Lattner996795b2006-06-28 23:17:24 +000047 struct VISIBILITY_HIDDEN SROA : public FunctionPass {
Chris Lattnerfb41a502003-05-27 15:45:27 +000048 bool runOnFunction(Function &F);
49
Chris Lattner5d8a12e2003-09-11 16:45:55 +000050 bool performScalarRepl(Function &F);
51 bool performPromotion(Function &F);
52
Chris Lattnerc8174582003-08-31 00:45:13 +000053 // getAnalysisUsage - This pass does not require any passes, but we know it
54 // will not alter the CFG, so say so.
55 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnera906bac2003-10-05 21:20:13 +000056 AU.addRequired<DominatorTree>();
Chris Lattner5d8a12e2003-09-11 16:45:55 +000057 AU.addRequired<DominanceFrontier>();
58 AU.addRequired<TargetData>();
Chris Lattnerc8174582003-08-31 00:45:13 +000059 AU.setPreservesCFG();
60 }
61
Chris Lattnerfb41a502003-05-27 15:45:27 +000062 private:
Chris Lattner877a3b42007-03-19 00:16:43 +000063 int isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI);
Chris Lattner66e6a822007-03-05 07:52:57 +000064 int isSafeUseOfAllocation(Instruction *User, AllocationInst *AI);
Chris Lattner877a3b42007-03-19 00:16:43 +000065 bool isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI);
Chris Lattner66e6a822007-03-05 07:52:57 +000066 bool isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI);
Chris Lattner88819122004-11-14 04:24:28 +000067 int isSafeAllocaToScalarRepl(AllocationInst *AI);
68 void CanonicalizeAllocaUsers(AllocationInst *AI);
Chris Lattnerfb41a502003-05-27 15:45:27 +000069 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
Chris Lattner3b0a62d2005-12-12 07:19:13 +000070
Chris Lattner877a3b42007-03-19 00:16:43 +000071 void RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
Chris Lattner66e6a822007-03-05 07:52:57 +000072 SmallVector<AllocaInst*, 32> &NewElts);
73
Chris Lattner3b0a62d2005-12-12 07:19:13 +000074 const Type *CanConvertToScalar(Value *V, bool &IsNotTrivial);
75 void ConvertToScalar(AllocationInst *AI, const Type *Ty);
76 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset);
Chris Lattnerfb41a502003-05-27 15:45:27 +000077 };
78
Chris Lattnerc2d3d312006-08-27 22:42:52 +000079 RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
Chris Lattnerfb41a502003-05-27 15:45:27 +000080}
81
Brian Gaeke960707c2003-11-11 22:41:34 +000082// Public interface to the ScalarReplAggregates pass
Chris Lattner3e860842004-09-20 04:43:15 +000083FunctionPass *llvm::createScalarReplAggregatesPass() { return new SROA(); }
Chris Lattnerfb41a502003-05-27 15:45:27 +000084
85
Chris Lattnerfb41a502003-05-27 15:45:27 +000086bool SROA::runOnFunction(Function &F) {
Chris Lattner9a95f2a2003-09-12 15:36:03 +000087 bool Changed = performPromotion(F);
88 while (1) {
89 bool LocalChange = performScalarRepl(F);
90 if (!LocalChange) break; // No need to repromote if no scalarrepl
91 Changed = true;
92 LocalChange = performPromotion(F);
93 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
94 }
Chris Lattner5d8a12e2003-09-11 16:45:55 +000095
96 return Changed;
97}
98
99
100bool SROA::performPromotion(Function &F) {
101 std::vector<AllocaInst*> Allocas;
102 const TargetData &TD = getAnalysis<TargetData>();
Chris Lattnera906bac2003-10-05 21:20:13 +0000103 DominatorTree &DT = getAnalysis<DominatorTree>();
104 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000105
Chris Lattner5dac64f2003-09-20 14:39:18 +0000106 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000107
Chris Lattner9a95f2a2003-09-12 15:36:03 +0000108 bool Changed = false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000109
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000110 while (1) {
111 Allocas.clear();
112
113 // Find allocas that are safe to promote, by looking at all instructions in
114 // the entry node
115 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
116 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
117 if (isAllocaPromotable(AI, TD))
118 Allocas.push_back(AI);
119
120 if (Allocas.empty()) break;
121
Chris Lattnera906bac2003-10-05 21:20:13 +0000122 PromoteMemToReg(Allocas, DT, DF, TD);
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000123 NumPromoted += Allocas.size();
124 Changed = true;
125 }
126
127 return Changed;
128}
129
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000130// performScalarRepl - This algorithm is a simple worklist driven algorithm,
131// which runs on all of the malloc/alloca instructions in the function, removing
132// them if they are only used by getelementptr instructions.
133//
134bool SROA::performScalarRepl(Function &F) {
Chris Lattnerfb41a502003-05-27 15:45:27 +0000135 std::vector<AllocationInst*> WorkList;
136
137 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
Chris Lattner5dac64f2003-09-20 14:39:18 +0000138 BasicBlock &BB = F.getEntryBlock();
Chris Lattnerfb41a502003-05-27 15:45:27 +0000139 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
140 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
141 WorkList.push_back(A);
142
143 // Process the worklist
144 bool Changed = false;
145 while (!WorkList.empty()) {
146 AllocationInst *AI = WorkList.back();
147 WorkList.pop_back();
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000148
Chris Lattnerf171af92006-12-22 23:14:42 +0000149 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
150 // with unused elements.
151 if (AI->use_empty()) {
152 AI->eraseFromParent();
153 continue;
154 }
155
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000156 // If we can turn this aggregate value (potentially with casts) into a
157 // simple scalar value that can be mem2reg'd into a register value.
158 bool IsNotTrivial = false;
159 if (const Type *ActualType = CanConvertToScalar(AI, IsNotTrivial))
Chris Lattnerdae49df2006-04-20 20:48:50 +0000160 if (IsNotTrivial && ActualType != Type::VoidTy) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000161 ConvertToScalar(AI, ActualType);
162 Changed = true;
163 continue;
164 }
Chris Lattnerfb41a502003-05-27 15:45:27 +0000165
166 // We cannot transform the allocation instruction if it is an array
Chris Lattnerc16b2102003-05-27 16:09:27 +0000167 // allocation (allocations OF arrays are ok though), and an allocation of a
168 // scalar value cannot be decomposed at all.
169 //
Chris Lattnerfb41a502003-05-27 15:45:27 +0000170 if (AI->isArrayAllocation() ||
Chris Lattnerc16b2102003-05-27 16:09:27 +0000171 (!isa<StructType>(AI->getAllocatedType()) &&
172 !isa<ArrayType>(AI->getAllocatedType()))) continue;
173
Chris Lattner6e5398d2003-05-30 04:15:41 +0000174 // Check that all of the users of the allocation are capable of being
175 // transformed.
Chris Lattner88819122004-11-14 04:24:28 +0000176 switch (isSafeAllocaToScalarRepl(AI)) {
177 default: assert(0 && "Unexpected value!");
178 case 0: // Not safe to scalar replace.
Chris Lattner6e5398d2003-05-30 04:15:41 +0000179 continue;
Chris Lattner88819122004-11-14 04:24:28 +0000180 case 1: // Safe, but requires cleanup/canonicalizations first
181 CanonicalizeAllocaUsers(AI);
182 case 3: // Safe to scalar replace.
183 break;
184 }
Chris Lattnerfb41a502003-05-27 15:45:27 +0000185
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000186 DOUT << "Found inst to xform: " << *AI;
Chris Lattnerfb41a502003-05-27 15:45:27 +0000187 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000188
Chris Lattner66e6a822007-03-05 07:52:57 +0000189 SmallVector<AllocaInst*, 32> ElementAllocas;
Chris Lattnerfb41a502003-05-27 15:45:27 +0000190 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
191 ElementAllocas.reserve(ST->getNumContainedTypes());
192 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Nate Begeman848622f2005-11-05 09:21:28 +0000193 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
194 AI->getAlignment(),
Chris Lattnerfb41a502003-05-27 15:45:27 +0000195 AI->getName() + "." + utostr(i), AI);
196 ElementAllocas.push_back(NA);
197 WorkList.push_back(NA); // Add to worklist for recursive processing
198 }
199 } else {
Chris Lattner6e5398d2003-05-30 04:15:41 +0000200 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
Chris Lattnerfb41a502003-05-27 15:45:27 +0000201 ElementAllocas.reserve(AT->getNumElements());
202 const Type *ElTy = AT->getElementType();
203 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Nate Begeman848622f2005-11-05 09:21:28 +0000204 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Chris Lattnerfb41a502003-05-27 15:45:27 +0000205 AI->getName() + "." + utostr(i), AI);
206 ElementAllocas.push_back(NA);
207 WorkList.push_back(NA); // Add to worklist for recursive processing
208 }
209 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000210
Chris Lattnerfb41a502003-05-27 15:45:27 +0000211 // Now that we have created the alloca instructions that we want to use,
212 // expand the getelementptr instructions to use them.
213 //
Chris Lattnerb5f8eb82004-06-19 02:02:22 +0000214 while (!AI->use_empty()) {
215 Instruction *User = cast<Instruction>(AI->use_back());
Chris Lattner66e6a822007-03-05 07:52:57 +0000216 if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
217 RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
Chris Lattner877a3b42007-03-19 00:16:43 +0000218 BCInst->eraseFromParent();
Chris Lattner66e6a822007-03-05 07:52:57 +0000219 continue;
220 }
221
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000222 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
223 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
Misha Brukmanb1c93172005-04-21 23:48:37 +0000224 unsigned Idx =
Reid Spencere0fc4df2006-10-20 07:07:24 +0000225 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000226
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000227 assert(Idx < ElementAllocas.size() && "Index out of range?");
228 AllocaInst *AllocaToUse = ElementAllocas[Idx];
Misha Brukmanb1c93172005-04-21 23:48:37 +0000229
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000230 Value *RepValue;
231 if (GEPI->getNumOperands() == 3) {
232 // Do not insert a new getelementptr instruction with zero indices, only
233 // to have it optimized out later.
234 RepValue = AllocaToUse;
Chris Lattnerfb41a502003-05-27 15:45:27 +0000235 } else {
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000236 // We are indexing deeply into the structure, so we still need a
237 // getelement ptr instruction to finish the indexing. This may be
238 // expanded itself once the worklist is rerun.
239 //
Chris Lattnera7315132007-02-12 22:56:41 +0000240 SmallVector<Value*, 8> NewArgs;
Reid Spencerc635f472006-12-31 05:48:39 +0000241 NewArgs.push_back(Constant::getNullValue(Type::Int32Ty));
Chris Lattnera7315132007-02-12 22:56:41 +0000242 NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
243 RepValue = new GetElementPtrInst(AllocaToUse, &NewArgs[0],
244 NewArgs.size(), "", GEPI);
Chris Lattner6e0123b2007-02-11 01:23:03 +0000245 RepValue->takeName(GEPI);
Chris Lattnerfb41a502003-05-27 15:45:27 +0000246 }
Chris Lattner877a3b42007-03-19 00:16:43 +0000247
248 // If this GEP is to the start of the aggregate, check for memcpys.
249 if (Idx == 0) {
250 bool IsStartOfAggregateGEP = true;
251 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i) {
252 if (!isa<ConstantInt>(GEPI->getOperand(i))) {
253 IsStartOfAggregateGEP = false;
254 break;
255 }
256 if (!cast<ConstantInt>(GEPI->getOperand(i))->isZero()) {
257 IsStartOfAggregateGEP = false;
258 break;
259 }
260 }
261
262 if (IsStartOfAggregateGEP)
263 RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas);
264 }
265
Misha Brukmanb1c93172005-04-21 23:48:37 +0000266
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000267 // Move all of the users over to the new GEP.
268 GEPI->replaceAllUsesWith(RepValue);
269 // Delete the old GEP
270 GEPI->eraseFromParent();
Chris Lattnerfb41a502003-05-27 15:45:27 +0000271 }
272
273 // Finally, delete the Alloca instruction
Chris Lattnerf171af92006-12-22 23:14:42 +0000274 AI->eraseFromParent();
Chris Lattnerc16b2102003-05-27 16:09:27 +0000275 NumReplaced++;
Chris Lattnerfb41a502003-05-27 15:45:27 +0000276 }
277
278 return Changed;
279}
Chris Lattner6e5398d2003-05-30 04:15:41 +0000280
281
Chris Lattner88819122004-11-14 04:24:28 +0000282/// isSafeElementUse - Check to see if this use is an allowed use for a
Chris Lattner877a3b42007-03-19 00:16:43 +0000283/// getelementptr instruction of an array aggregate allocation. isFirstElt
284/// indicates whether Ptr is known to the start of the aggregate.
Chris Lattner88819122004-11-14 04:24:28 +0000285///
Chris Lattner877a3b42007-03-19 00:16:43 +0000286int SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI) {
Chris Lattner88819122004-11-14 04:24:28 +0000287 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
288 I != E; ++I) {
289 Instruction *User = cast<Instruction>(*I);
290 switch (User->getOpcode()) {
291 case Instruction::Load: break;
292 case Instruction::Store:
293 // Store is ok if storing INTO the pointer, not storing the pointer
294 if (User->getOperand(0) == Ptr) return 0;
295 break;
296 case Instruction::GetElementPtr: {
297 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
Chris Lattner877a3b42007-03-19 00:16:43 +0000298 bool AreAllZeroIndices = isFirstElt;
Chris Lattner88819122004-11-14 04:24:28 +0000299 if (GEP->getNumOperands() > 1) {
Chris Lattner877a3b42007-03-19 00:16:43 +0000300 if (!isa<ConstantInt>(GEP->getOperand(1)) ||
301 !cast<ConstantInt>(GEP->getOperand(1))->isZero())
302 return 0; // Using pointer arithmetic to navigate the array.
303
304 if (AreAllZeroIndices) {
305 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) {
306 if (!isa<ConstantInt>(GEP->getOperand(i)) ||
307 !cast<ConstantInt>(GEP->getOperand(i))->isZero()) {
308 AreAllZeroIndices = false;
309 break;
310 }
311 }
312 }
Chris Lattner88819122004-11-14 04:24:28 +0000313 }
Chris Lattner877a3b42007-03-19 00:16:43 +0000314 if (!isSafeElementUse(GEP, AreAllZeroIndices, AI)) return 0;
Chris Lattner88819122004-11-14 04:24:28 +0000315 break;
316 }
Chris Lattner877a3b42007-03-19 00:16:43 +0000317 case Instruction::BitCast:
318 if (isFirstElt &&
319 isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI))
320 break;
321 DOUT << " Transformation preventing inst: " << *User;
322 return 0;
323 case Instruction::Call:
324 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
325 if (isFirstElt && isSafeMemIntrinsicOnAllocation(MI, AI))
326 break;
327 }
328 DOUT << " Transformation preventing inst: " << *User;
329 return 0;
Chris Lattner88819122004-11-14 04:24:28 +0000330 default:
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000331 DOUT << " Transformation preventing inst: " << *User;
Chris Lattner88819122004-11-14 04:24:28 +0000332 return 0;
333 }
334 }
335 return 3; // All users look ok :)
336}
337
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000338/// AllUsersAreLoads - Return true if all users of this value are loads.
339static bool AllUsersAreLoads(Value *Ptr) {
340 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
341 I != E; ++I)
342 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
343 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000344 return true;
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000345}
346
Chris Lattner6e5398d2003-05-30 04:15:41 +0000347/// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
348/// aggregate allocation.
349///
Chris Lattner66e6a822007-03-05 07:52:57 +0000350int SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI) {
351 if (BitCastInst *C = dyn_cast<BitCastInst>(User))
Chris Lattnerabd3bff2007-03-08 07:03:55 +0000352 return isSafeUseOfBitCastedAllocation(C, AI) ? 3 : 0;
Chris Lattner88819122004-11-14 04:24:28 +0000353 if (!isa<GetElementPtrInst>(User)) return 0;
Chris Lattner52310702003-11-25 21:09:18 +0000354
355 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
356 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
357
Chris Lattnerfc34f8b2006-03-08 01:05:29 +0000358 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
Chris Lattner52310702003-11-25 21:09:18 +0000359 if (I == E ||
360 I.getOperand() != Constant::getNullValue(I.getOperand()->getType()))
Chris Lattner88819122004-11-14 04:24:28 +0000361 return 0;
Chris Lattner52310702003-11-25 21:09:18 +0000362
363 ++I;
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000364 if (I == E) return 0; // ran out of GEP indices??
Chris Lattner52310702003-11-25 21:09:18 +0000365
Chris Lattner877a3b42007-03-19 00:16:43 +0000366 bool IsAllZeroIndices = true;
367
Chris Lattner52310702003-11-25 21:09:18 +0000368 // If this is a use of an array allocation, do a bit more checking for sanity.
369 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
370 uint64_t NumElements = AT->getNumElements();
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000371
Chris Lattner877a3b42007-03-19 00:16:43 +0000372 if (ConstantInt *Idx = dyn_cast<ConstantInt>(I.getOperand())) {
373 IsAllZeroIndices &= Idx->isZero();
374
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000375 // Check to make sure that index falls within the array. If not,
376 // something funny is going on, so we won't do the optimization.
377 //
Chris Lattner877a3b42007-03-19 00:16:43 +0000378 if (Idx->getZExtValue() >= NumElements)
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000379 return 0;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000380
Chris Lattnerfc34f8b2006-03-08 01:05:29 +0000381 // We cannot scalar repl this level of the array unless any array
382 // sub-indices are in-range constants. In particular, consider:
383 // A[0][i]. We cannot know that the user isn't doing invalid things like
384 // allowing i to index an out-of-range subscript that accesses A[1].
385 //
386 // Scalar replacing *just* the outer index of the array is probably not
387 // going to be a win anyway, so just give up.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000388 for (++I; I != E && (isa<ArrayType>(*I) || isa<VectorType>(*I)); ++I) {
Chris Lattner4967f6d2006-11-07 22:42:47 +0000389 uint64_t NumElements;
390 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*I))
391 NumElements = SubArrayTy->getNumElements();
392 else
Reid Spencerd84d35b2007-02-15 02:26:10 +0000393 NumElements = cast<VectorType>(*I)->getNumElements();
Chris Lattner4967f6d2006-11-07 22:42:47 +0000394
Chris Lattner877a3b42007-03-19 00:16:43 +0000395 ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
396 if (!IdxVal) return 0;
397 if (IdxVal->getZExtValue() >= NumElements)
Chris Lattnerfc34f8b2006-03-08 01:05:29 +0000398 return 0;
Chris Lattner877a3b42007-03-19 00:16:43 +0000399 IsAllZeroIndices &= IdxVal->isZero();
Chris Lattnerfc34f8b2006-03-08 01:05:29 +0000400 }
401
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000402 } else {
Chris Lattner877a3b42007-03-19 00:16:43 +0000403 IsAllZeroIndices = 0;
404
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000405 // If this is an array index and the index is not constant, we cannot
406 // promote... that is unless the array has exactly one or two elements in
407 // it, in which case we CAN promote it, but we have to canonicalize this
408 // out if this is the only problem.
Chris Lattnerfc34f8b2006-03-08 01:05:29 +0000409 if ((NumElements == 1 || NumElements == 2) &&
410 AllUsersAreLoads(GEPI))
411 return 1; // Canonicalization required!
Chris Lattner88819122004-11-14 04:24:28 +0000412 return 0;
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000413 }
Chris Lattner6e5398d2003-05-30 04:15:41 +0000414 }
Chris Lattner52310702003-11-25 21:09:18 +0000415
416 // If there are any non-simple uses of this getelementptr, make sure to reject
417 // them.
Chris Lattner877a3b42007-03-19 00:16:43 +0000418 return isSafeElementUse(GEPI, IsAllZeroIndices, AI);
419}
420
421/// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
422/// intrinsic can be promoted by SROA. At this point, we know that the operand
423/// of the memintrinsic is a pointer to the beginning of the allocation.
424bool SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI){
425 // If not constant length, give up.
426 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
427 if (!Length) return false;
428
429 // If not the whole aggregate, give up.
430 const TargetData &TD = getAnalysis<TargetData>();
431 if (Length->getZExtValue() != TD.getTypeSize(AI->getType()->getElementType()))
432 return false;
433
434 // We only know about memcpy/memset/memmove.
435 if (!isa<MemCpyInst>(MI) && !isa<MemSetInst>(MI) && !isa<MemMoveInst>(MI))
436 return false;
437 // Otherwise, we can transform it.
438 return true;
Chris Lattner6e5398d2003-05-30 04:15:41 +0000439}
440
Chris Lattner66e6a822007-03-05 07:52:57 +0000441/// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
442/// are
443bool SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI) {
444 for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
445 UI != E; ++UI) {
446 if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
447 if (!isSafeUseOfBitCastedAllocation(BCU, AI))
448 return false;
449 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
Chris Lattner877a3b42007-03-19 00:16:43 +0000450 if (!isSafeMemIntrinsicOnAllocation(MI, AI))
Chris Lattner66e6a822007-03-05 07:52:57 +0000451 return false;
Chris Lattner66e6a822007-03-05 07:52:57 +0000452 } else {
453 return false;
454 }
455 }
456 return true;
457}
458
Chris Lattner877a3b42007-03-19 00:16:43 +0000459/// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
460/// to its first element. Transform users of the cast to use the new values
461/// instead.
462void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
Chris Lattner66e6a822007-03-05 07:52:57 +0000463 SmallVector<AllocaInst*, 32> &NewElts) {
464 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
465 const TargetData &TD = getAnalysis<TargetData>();
Chris Lattner877a3b42007-03-19 00:16:43 +0000466
467 Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
468 while (UI != UE) {
469 if (BitCastInst *BCU = dyn_cast<BitCastInst>(*UI)) {
Chris Lattner66e6a822007-03-05 07:52:57 +0000470 RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
Chris Lattner877a3b42007-03-19 00:16:43 +0000471 ++UI;
472 BCU->eraseFromParent();
Chris Lattner66e6a822007-03-05 07:52:57 +0000473 continue;
474 }
475
476 // Otherwise, must be memcpy/memmove/memset of the entire aggregate. Split
477 // into one per element.
Chris Lattner877a3b42007-03-19 00:16:43 +0000478 MemIntrinsic *MI = dyn_cast<MemIntrinsic>(*UI);
479
480 // If it's not a mem intrinsic, it must be some other user of a gep of the
481 // first pointer. Just leave these alone.
482 if (!MI) {
483 ++UI;
484 continue;
485 }
Chris Lattner66e6a822007-03-05 07:52:57 +0000486
487 // If this is a memcpy/memmove, construct the other pointer as the
488 // appropriate type.
489 Value *OtherPtr = 0;
490 if (MemCpyInst *MCI = dyn_cast<MemCpyInst>(MI)) {
491 if (BCInst == MCI->getRawDest())
492 OtherPtr = MCI->getRawSource();
493 else {
494 assert(BCInst == MCI->getRawSource());
495 OtherPtr = MCI->getRawDest();
496 }
497 } else if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
498 if (BCInst == MMI->getRawDest())
499 OtherPtr = MMI->getRawSource();
500 else {
501 assert(BCInst == MMI->getRawSource());
502 OtherPtr = MMI->getRawDest();
503 }
504 }
505
506 // If there is an other pointer, we want to convert it to the same pointer
507 // type as AI has, so we can GEP through it.
508 if (OtherPtr) {
509 // It is likely that OtherPtr is a bitcast, if so, remove it.
510 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
511 OtherPtr = BC->getOperand(0);
512 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
513 if (BCE->getOpcode() == Instruction::BitCast)
514 OtherPtr = BCE->getOperand(0);
515
516 // If the pointer is not the right type, insert a bitcast to the right
517 // type.
518 if (OtherPtr->getType() != AI->getType())
519 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
520 MI);
521 }
522
523 // Process each element of the aggregate.
524 Value *TheFn = MI->getOperand(0);
525 const Type *BytePtrTy = MI->getRawDest()->getType();
526 bool SROADest = MI->getRawDest() == BCInst;
527
528 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
529 // If this is a memcpy/memmove, emit a GEP of the other element address.
530 Value *OtherElt = 0;
531 if (OtherPtr) {
532 OtherElt = new GetElementPtrInst(OtherPtr, Zero,
533 ConstantInt::get(Type::Int32Ty, i),
534 OtherPtr->getNameStr()+"."+utostr(i),
535 MI);
Chris Lattner66e6a822007-03-05 07:52:57 +0000536 }
537
538 Value *EltPtr = NewElts[i];
Chris Lattner9f022d52007-03-08 06:36:54 +0000539 const Type *EltTy =cast<PointerType>(EltPtr->getType())->getElementType();
540
541 // If we got down to a scalar, insert a load or store as appropriate.
542 if (EltTy->isFirstClassType()) {
543 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
544 Value *Elt = new LoadInst(SROADest ? OtherElt : EltPtr, "tmp",
545 MI);
546 new StoreInst(Elt, SROADest ? EltPtr : OtherElt, MI);
547 continue;
548 } else {
549 assert(isa<MemSetInst>(MI));
550
551 // If the stored element is zero (common case), just store a null
552 // constant.
553 Constant *StoreVal;
554 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
555 if (CI->isZero()) {
556 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
557 } else {
558 // If EltTy is a packed type, get the element type.
559 const Type *ValTy = EltTy;
560 if (const VectorType *VTy = dyn_cast<VectorType>(ValTy))
561 ValTy = VTy->getElementType();
562
563 // Construct an integer with the right value.
564 unsigned EltSize = TD.getTypeSize(ValTy);
565 APInt OneVal(EltSize*8, CI->getZExtValue());
566 APInt TotalVal(OneVal);
567 // Set each byte.
568 for (unsigned i = 0; i != EltSize-1; ++i) {
569 TotalVal = TotalVal.shl(8);
570 TotalVal |= OneVal;
571 }
572
573 // Convert the integer value to the appropriate type.
574 StoreVal = ConstantInt::get(TotalVal);
575 if (isa<PointerType>(ValTy))
576 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
577 else if (ValTy->isFloatingPoint())
578 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
579 assert(StoreVal->getType() == ValTy && "Type mismatch!");
580
581 // If the requested value was a vector constant, create it.
582 if (EltTy != ValTy) {
583 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
584 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
585 StoreVal = ConstantVector::get(&Elts[0], NumElts);
586 }
587 }
588 new StoreInst(StoreVal, EltPtr, MI);
589 continue;
590 }
591 // Otherwise, if we're storing a byte variable, use a memset call for
592 // this element.
593 }
594 }
Chris Lattner66e6a822007-03-05 07:52:57 +0000595
596 // Cast the element pointer to BytePtrTy.
597 if (EltPtr->getType() != BytePtrTy)
598 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
Chris Lattner9f022d52007-03-08 06:36:54 +0000599
600 // Cast the other pointer (if we have one) to BytePtrTy.
601 if (OtherElt && OtherElt->getType() != BytePtrTy)
602 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
603 MI);
604
605 unsigned EltSize = TD.getTypeSize(EltTy);
606
Chris Lattner66e6a822007-03-05 07:52:57 +0000607 // Finally, insert the meminst for this element.
608 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
609 Value *Ops[] = {
610 SROADest ? EltPtr : OtherElt, // Dest ptr
611 SROADest ? OtherElt : EltPtr, // Src ptr
612 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
613 Zero // Align
614 };
615 new CallInst(TheFn, Ops, 4, "", MI);
Chris Lattner9f022d52007-03-08 06:36:54 +0000616 } else {
617 assert(isa<MemSetInst>(MI));
Chris Lattner66e6a822007-03-05 07:52:57 +0000618 Value *Ops[] = {
619 EltPtr, MI->getOperand(2), // Dest, Value,
620 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
621 Zero // Align
622 };
623 new CallInst(TheFn, Ops, 4, "", MI);
624 }
Chris Lattner9f022d52007-03-08 06:36:54 +0000625 }
Chris Lattner66e6a822007-03-05 07:52:57 +0000626
627 // Finally, MI is now dead, as we've modified its actions to occur on all of
628 // the elements of the aggregate.
Chris Lattner877a3b42007-03-19 00:16:43 +0000629 ++UI;
Chris Lattner66e6a822007-03-05 07:52:57 +0000630 MI->eraseFromParent();
631 }
Chris Lattner66e6a822007-03-05 07:52:57 +0000632}
633
634
Chris Lattner88819122004-11-14 04:24:28 +0000635/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
636/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
637/// or 1 if safe after canonicalization has been performed.
Chris Lattner6e5398d2003-05-30 04:15:41 +0000638///
Chris Lattner88819122004-11-14 04:24:28 +0000639int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
Chris Lattner6e5398d2003-05-30 04:15:41 +0000640 // Loop over the use list of the alloca. We can only transform it if all of
641 // the users are safe to transform.
642 //
Chris Lattner88819122004-11-14 04:24:28 +0000643 int isSafe = 3;
Chris Lattner6e5398d2003-05-30 04:15:41 +0000644 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
Chris Lattner88819122004-11-14 04:24:28 +0000645 I != E; ++I) {
Chris Lattner66e6a822007-03-05 07:52:57 +0000646 isSafe &= isSafeUseOfAllocation(cast<Instruction>(*I), AI);
Chris Lattner88819122004-11-14 04:24:28 +0000647 if (isSafe == 0) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000648 DOUT << "Cannot transform: " << *AI << " due to user: " << **I;
Chris Lattner88819122004-11-14 04:24:28 +0000649 return 0;
Chris Lattner6e5398d2003-05-30 04:15:41 +0000650 }
Chris Lattner88819122004-11-14 04:24:28 +0000651 }
652 // If we require cleanup, isSafe is now 1, otherwise it is 3.
653 return isSafe;
654}
655
656/// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified
657/// allocation, but only if cleaned up, perform the cleanups required.
658void SROA::CanonicalizeAllocaUsers(AllocationInst *AI) {
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000659 // At this point, we know that the end result will be SROA'd and promoted, so
660 // we can insert ugly code if required so long as sroa+mem2reg will clean it
661 // up.
662 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
663 UI != E; ) {
Chris Lattner9c62db72007-03-19 18:25:57 +0000664 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI++);
665 if (!GEPI) continue;
Reid Spencer93396382004-11-15 17:29:41 +0000666 gep_type_iterator I = gep_type_begin(GEPI);
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000667 ++I;
Chris Lattner88819122004-11-14 04:24:28 +0000668
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000669 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
670 uint64_t NumElements = AT->getNumElements();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000671
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000672 if (!isa<ConstantInt>(I.getOperand())) {
673 if (NumElements == 1) {
Reid Spencerc635f472006-12-31 05:48:39 +0000674 GEPI->setOperand(2, Constant::getNullValue(Type::Int32Ty));
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000675 } else {
676 assert(NumElements == 2 && "Unhandled case!");
677 // All users of the GEP must be loads. At each use of the GEP, insert
678 // two loads of the appropriate indexed GEP and select between them.
Reid Spencer266e42b2006-12-23 06:05:41 +0000679 Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(),
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000680 Constant::getNullValue(I.getOperand()->getType()),
Reid Spencer266e42b2006-12-23 06:05:41 +0000681 "isone", GEPI);
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000682 // Insert the new GEP instructions, which are properly indexed.
Chris Lattnera7315132007-02-12 22:56:41 +0000683 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
Reid Spencerc635f472006-12-31 05:48:39 +0000684 Indices[1] = Constant::getNullValue(Type::Int32Ty);
Chris Lattnera7315132007-02-12 22:56:41 +0000685 Value *ZeroIdx = new GetElementPtrInst(GEPI->getOperand(0),
686 &Indices[0], Indices.size(),
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000687 GEPI->getName()+".0", GEPI);
Reid Spencerc635f472006-12-31 05:48:39 +0000688 Indices[1] = ConstantInt::get(Type::Int32Ty, 1);
Chris Lattnera7315132007-02-12 22:56:41 +0000689 Value *OneIdx = new GetElementPtrInst(GEPI->getOperand(0),
690 &Indices[0], Indices.size(),
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000691 GEPI->getName()+".1", GEPI);
692 // Replace all loads of the variable index GEP with loads from both
693 // indexes and a select.
694 while (!GEPI->use_empty()) {
695 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
696 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
697 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
698 Value *R = new SelectInst(IsOne, One, Zero, LI->getName(), LI);
699 LI->replaceAllUsesWith(R);
700 LI->eraseFromParent();
701 }
702 GEPI->eraseFromParent();
703 }
704 }
705 }
706 }
Chris Lattner6e5398d2003-05-30 04:15:41 +0000707}
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000708
709/// MergeInType - Add the 'In' type to the accumulated type so far. If the
710/// types are incompatible, return true, otherwise update Accum and return
711/// false.
Chris Lattner3323ce12006-04-14 21:42:41 +0000712///
Chris Lattner8f7b7752006-12-15 07:32:38 +0000713/// There are three cases we handle here:
714/// 1) An effectively-integer union, where the pieces are stored into as
Chris Lattner3323ce12006-04-14 21:42:41 +0000715/// smaller integers (common with byte swap and other idioms).
Chris Lattner8f7b7752006-12-15 07:32:38 +0000716/// 2) A union of vector types of the same size and potentially its elements.
717/// Here we turn element accesses into insert/extract element operations.
718/// 3) A union of scalar types, such as int/float or int/pointer. Here we
719/// merge together into integers, allowing the xform to work with #1 as
720/// well.
Chris Lattner05f82722006-10-08 23:28:04 +0000721static bool MergeInType(const Type *In, const Type *&Accum,
722 const TargetData &TD) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000723 // If this is our first type, just use it.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000724 const VectorType *PTy;
Chris Lattner3323ce12006-04-14 21:42:41 +0000725 if (Accum == Type::VoidTy || In == Accum) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000726 Accum = In;
Chris Lattner8f7b7752006-12-15 07:32:38 +0000727 } else if (In == Type::VoidTy) {
728 // Noop.
Chris Lattner03c49532007-01-15 02:27:26 +0000729 } else if (In->isInteger() && Accum->isInteger()) { // integer union.
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000730 // Otherwise pick whichever type is larger.
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000731 if (cast<IntegerType>(In)->getBitWidth() >
732 cast<IntegerType>(Accum)->getBitWidth())
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000733 Accum = In;
Chris Lattner05f82722006-10-08 23:28:04 +0000734 } else if (isa<PointerType>(In) && isa<PointerType>(Accum)) {
Chris Lattner41b44222006-10-08 23:53:04 +0000735 // Pointer unions just stay as one of the pointers.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000736 } else if (isa<VectorType>(In) || isa<VectorType>(Accum)) {
737 if ((PTy = dyn_cast<VectorType>(Accum)) &&
Chris Lattner8f7b7752006-12-15 07:32:38 +0000738 PTy->getElementType() == In) {
739 // Accum is a vector, and we are accessing an element: ok.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000740 } else if ((PTy = dyn_cast<VectorType>(In)) &&
Chris Lattner8f7b7752006-12-15 07:32:38 +0000741 PTy->getElementType() == Accum) {
742 // In is a vector, and accum is an element: ok, remember In.
743 Accum = In;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000744 } else if ((PTy = dyn_cast<VectorType>(In)) && isa<VectorType>(Accum) &&
745 PTy->getBitWidth() == cast<VectorType>(Accum)->getBitWidth()) {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000746 // Two vectors of the same size: keep Accum.
747 } else {
748 // Cannot insert an short into a <4 x int> or handle
749 // <2 x int> -> <4 x int>
750 return true;
751 }
Chris Lattner7c1dff92006-12-13 02:26:45 +0000752 } else {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000753 // Pointer/FP/Integer unions merge together as integers.
754 switch (Accum->getTypeID()) {
755 case Type::PointerTyID: Accum = TD.getIntPtrType(); break;
Reid Spencerc635f472006-12-31 05:48:39 +0000756 case Type::FloatTyID: Accum = Type::Int32Ty; break;
757 case Type::DoubleTyID: Accum = Type::Int64Ty; break;
Chris Lattner8f7b7752006-12-15 07:32:38 +0000758 default:
Chris Lattner03c49532007-01-15 02:27:26 +0000759 assert(Accum->isInteger() && "Unknown FP type!");
Chris Lattner8f7b7752006-12-15 07:32:38 +0000760 break;
761 }
762
763 switch (In->getTypeID()) {
764 case Type::PointerTyID: In = TD.getIntPtrType(); break;
Reid Spencerc635f472006-12-31 05:48:39 +0000765 case Type::FloatTyID: In = Type::Int32Ty; break;
766 case Type::DoubleTyID: In = Type::Int64Ty; break;
Chris Lattner8f7b7752006-12-15 07:32:38 +0000767 default:
Chris Lattner03c49532007-01-15 02:27:26 +0000768 assert(In->isInteger() && "Unknown FP type!");
Chris Lattner8f7b7752006-12-15 07:32:38 +0000769 break;
770 }
771 return MergeInType(In, Accum, TD);
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000772 }
773 return false;
774}
775
776/// getUIntAtLeastAsBitAs - Return an unsigned integer type that is at least
777/// as big as the specified type. If there is no suitable type, this returns
778/// null.
779const Type *getUIntAtLeastAsBitAs(unsigned NumBits) {
780 if (NumBits > 64) return 0;
Reid Spencerc635f472006-12-31 05:48:39 +0000781 if (NumBits > 32) return Type::Int64Ty;
782 if (NumBits > 16) return Type::Int32Ty;
783 if (NumBits > 8) return Type::Int16Ty;
784 return Type::Int8Ty;
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000785}
786
787/// CanConvertToScalar - V is a pointer. If we can convert the pointee to a
788/// single scalar integer type, return that type. Further, if the use is not
789/// a completely trivial use that mem2reg could promote, set IsNotTrivial. If
790/// there are no uses of this pointer, return Type::VoidTy to differentiate from
791/// failure.
792///
793const Type *SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial) {
794 const Type *UsedType = Type::VoidTy; // No uses, no forced type.
795 const TargetData &TD = getAnalysis<TargetData>();
796 const PointerType *PTy = cast<PointerType>(V->getType());
797
798 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
799 Instruction *User = cast<Instruction>(*UI);
800
801 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner05f82722006-10-08 23:28:04 +0000802 if (MergeInType(LI->getType(), UsedType, TD))
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000803 return 0;
804
805 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Reid Spencer2eadb532007-01-21 00:29:26 +0000806 // Storing the pointer, not into the value?
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000807 if (SI->getOperand(0) == V) return 0;
808
Chris Lattner3323ce12006-04-14 21:42:41 +0000809 // NOTE: We could handle storing of FP imms into integers here!
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000810
Chris Lattner05f82722006-10-08 23:28:04 +0000811 if (MergeInType(SI->getOperand(0)->getType(), UsedType, TD))
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000812 return 0;
Chris Lattner8f7b7752006-12-15 07:32:38 +0000813 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000814 IsNotTrivial = true;
815 const Type *SubTy = CanConvertToScalar(CI, IsNotTrivial);
Chris Lattner05f82722006-10-08 23:28:04 +0000816 if (!SubTy || MergeInType(SubTy, UsedType, TD)) return 0;
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000817 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
818 // Check to see if this is stepping over an element: GEP Ptr, int C
819 if (GEP->getNumOperands() == 2 && isa<ConstantInt>(GEP->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000820 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000821 unsigned ElSize = TD.getTypeSize(PTy->getElementType());
822 unsigned BitOffset = Idx*ElSize*8;
823 if (BitOffset > 64 || !isPowerOf2_32(ElSize)) return 0;
824
825 IsNotTrivial = true;
826 const Type *SubElt = CanConvertToScalar(GEP, IsNotTrivial);
827 if (SubElt == 0) return 0;
Chris Lattner03c49532007-01-15 02:27:26 +0000828 if (SubElt != Type::VoidTy && SubElt->isInteger()) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000829 const Type *NewTy =
Chris Lattner41b44222006-10-08 23:53:04 +0000830 getUIntAtLeastAsBitAs(TD.getTypeSize(SubElt)*8+BitOffset);
Chris Lattner05f82722006-10-08 23:28:04 +0000831 if (NewTy == 0 || MergeInType(NewTy, UsedType, TD)) return 0;
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000832 continue;
833 }
834 } else if (GEP->getNumOperands() == 3 &&
835 isa<ConstantInt>(GEP->getOperand(1)) &&
836 isa<ConstantInt>(GEP->getOperand(2)) &&
Zhou Shengaafe4e22007-04-19 05:39:12 +0000837 cast<ConstantInt>(GEP->getOperand(1))->isZero()) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000838 // We are stepping into an element, e.g. a structure or an array:
839 // GEP Ptr, int 0, uint C
840 const Type *AggTy = PTy->getElementType();
Reid Spencere0fc4df2006-10-20 07:07:24 +0000841 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000842
843 if (const ArrayType *ATy = dyn_cast<ArrayType>(AggTy)) {
844 if (Idx >= ATy->getNumElements()) return 0; // Out of range.
Reid Spencer09575ba2007-02-15 03:39:18 +0000845 } else if (const VectorType *VectorTy = dyn_cast<VectorType>(AggTy)) {
Chris Lattner3323ce12006-04-14 21:42:41 +0000846 // Getting an element of the packed vector.
Reid Spencer09575ba2007-02-15 03:39:18 +0000847 if (Idx >= VectorTy->getNumElements()) return 0; // Out of range.
Chris Lattner3323ce12006-04-14 21:42:41 +0000848
Reid Spencer09575ba2007-02-15 03:39:18 +0000849 // Merge in the vector type.
850 if (MergeInType(VectorTy, UsedType, TD)) return 0;
Chris Lattner3323ce12006-04-14 21:42:41 +0000851
852 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
853 if (SubTy == 0) return 0;
854
Chris Lattner05f82722006-10-08 23:28:04 +0000855 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
Chris Lattner3323ce12006-04-14 21:42:41 +0000856 return 0;
857
858 // We'll need to change this to an insert/extract element operation.
859 IsNotTrivial = true;
860 continue; // Everything looks ok
861
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000862 } else if (isa<StructType>(AggTy)) {
863 // Structs are always ok.
864 } else {
865 return 0;
866 }
867 const Type *NTy = getUIntAtLeastAsBitAs(TD.getTypeSize(AggTy)*8);
Chris Lattner05f82722006-10-08 23:28:04 +0000868 if (NTy == 0 || MergeInType(NTy, UsedType, TD)) return 0;
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000869 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
870 if (SubTy == 0) return 0;
Chris Lattner05f82722006-10-08 23:28:04 +0000871 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000872 return 0;
873 continue; // Everything looks ok
874 }
875 return 0;
876 } else {
877 // Cannot handle this!
878 return 0;
879 }
880 }
881
882 return UsedType;
883}
884
885/// ConvertToScalar - The specified alloca passes the CanConvertToScalar
886/// predicate and is non-trivial. Convert it to something that can be trivially
887/// promoted into a register by mem2reg.
888void SROA::ConvertToScalar(AllocationInst *AI, const Type *ActualTy) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000889 DOUT << "CONVERT TO SCALAR: " << *AI << " TYPE = "
890 << *ActualTy << "\n";
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000891 ++NumConverted;
892
893 BasicBlock *EntryBlock = AI->getParent();
Dan Gohmandcb291f2007-03-22 16:38:57 +0000894 assert(EntryBlock == &EntryBlock->getParent()->getEntryBlock() &&
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000895 "Not in the entry block!");
896 EntryBlock->getInstList().remove(AI); // Take the alloca out of the program.
897
898 // Create and insert the alloca.
Chris Lattner3323ce12006-04-14 21:42:41 +0000899 AllocaInst *NewAI = new AllocaInst(ActualTy, 0, AI->getName(),
900 EntryBlock->begin());
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000901 ConvertUsesToScalar(AI, NewAI, 0);
902 delete AI;
903}
904
905
906/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
Chris Lattner3323ce12006-04-14 21:42:41 +0000907/// directly. This happens when we are converting an "integer union" to a
908/// single integer scalar, or when we are converting a "vector union" to a
909/// vector with insert/extractelement instructions.
910///
911/// Offset is an offset from the original alloca, in bits that need to be
912/// shifted to the right. By the end of this, there should be no uses of Ptr.
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000913void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset) {
Chris Lattner41b44222006-10-08 23:53:04 +0000914 const TargetData &TD = getAnalysis<TargetData>();
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000915 while (!Ptr->use_empty()) {
916 Instruction *User = cast<Instruction>(Ptr->use_back());
917
918 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
919 // The load is a bit extract from NewAI shifted right by Offset bits.
920 Value *NV = new LoadInst(NewAI, LI->getName(), LI);
Chris Lattnerdaa012d2007-04-11 00:57:54 +0000921 if (NV->getType() == LI->getType()) {
922 // We win, no conversion needed.
923 } else if (const VectorType *PTy = dyn_cast<VectorType>(NV->getType())) {
924 // If the result alloca is a vector type, this is either an element
925 // access or a bitcast to another vector type.
926 if (isa<VectorType>(LI->getType())) {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000927 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
928 } else {
Chris Lattnerdaa012d2007-04-11 00:57:54 +0000929 // Must be an element access.
930 unsigned Elt = Offset/(TD.getTypeSize(PTy->getElementType())*8);
931 NV = new ExtractElementInst(
932 NV, ConstantInt::get(Type::Int32Ty, Elt), "tmp", LI);
933 }
934 } else if (isa<PointerType>(NV->getType())) {
935 assert(isa<PointerType>(LI->getType()));
936 // Must be ptr->ptr cast. Anything else would result in NV being
937 // an integer.
938 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
939 } else {
940 const IntegerType *NTy = cast<IntegerType>(NV->getType());
941 unsigned LIBitWidth = TD.getTypeSizeInBits(LI->getType());
942
943 // If this is a big-endian system and the load is narrower than the
944 // full alloca type, we need to do a shift to get the right bits.
945 int ShAmt = 0;
946 if (TD.isBigEndian()) {
947 ShAmt = NTy->getBitWidth()-LIBitWidth-Offset;
948 } else {
949 ShAmt = Offset;
950 }
951
952 // Note: we support negative bitwidths (with shl) which are not defined.
953 // We do this to support (f.e.) loads off the end of a structure where
954 // only some bits are used.
955 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
956 NV = BinaryOperator::createLShr(NV,
957 ConstantInt::get(NV->getType(),ShAmt),
958 LI->getName(), LI);
959 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
960 NV = BinaryOperator::createShl(NV,
961 ConstantInt::get(NV->getType(),-ShAmt),
962 LI->getName(), LI);
963
964 // Finally, unconditionally truncate the integer to the right width.
965 if (LIBitWidth < NTy->getBitWidth())
966 NV = new TruncInst(NV, IntegerType::get(LIBitWidth),
967 LI->getName(), LI);
968
969 // If the result is an integer, this is a trunc or bitcast.
970 if (isa<IntegerType>(LI->getType())) {
971 assert(NV->getType() == LI->getType() && "Truncate wasn't enough?");
972 } else if (LI->getType()->isFloatingPoint()) {
Chris Lattner32104032007-04-11 03:27:24 +0000973 // Just do a bitcast, we know the sizes match up.
Chris Lattnerdaa012d2007-04-11 00:57:54 +0000974 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
975 } else {
976 // Otherwise must be a pointer.
977 NV = new IntToPtrInst(NV, LI->getType(), LI->getName(), LI);
Chris Lattner3323ce12006-04-14 21:42:41 +0000978 }
979 }
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000980 LI->replaceAllUsesWith(NV);
981 LI->eraseFromParent();
982 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
983 assert(SI->getOperand(0) != Ptr && "Consistency error!");
984
985 // Convert the stored type to the actual type, shift it left to insert
986 // then 'or' into place.
987 Value *SV = SI->getOperand(0);
Chris Lattner3323ce12006-04-14 21:42:41 +0000988 const Type *AllocaType = NewAI->getType()->getElementType();
Chris Lattnerdaa012d2007-04-11 00:57:54 +0000989 if (SV->getType() == AllocaType) {
990 // All is well.
991 } else if (const VectorType *PTy = dyn_cast<VectorType>(AllocaType)) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000992 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
Chris Lattnerdaa012d2007-04-11 00:57:54 +0000993
994 // If the result alloca is a vector type, this is either an element
995 // access or a bitcast to another vector type.
996 if (isa<VectorType>(SV->getType())) {
997 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
998 } else {
999 // Must be an element insertion.
1000 unsigned Elt = Offset/(TD.getTypeSize(PTy->getElementType())*8);
1001 SV = new InsertElementInst(Old, SV,
1002 ConstantInt::get(Type::Int32Ty, Elt),
1003 "tmp", SI);
1004 }
Chris Lattner5ee4d072007-04-11 15:45:25 +00001005 } else if (isa<PointerType>(AllocaType)) {
1006 // If the alloca type is a pointer, then all the elements must be
1007 // pointers.
1008 if (SV->getType() != AllocaType)
1009 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
Chris Lattnerdaa012d2007-04-11 00:57:54 +00001010 } else {
1011 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1012
1013 // If SV is a float, convert it to the appropriate integer type.
1014 // If it is a pointer, do the same, and also handle ptr->ptr casts
1015 // here.
1016 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
1017 unsigned DestWidth = AllocaType->getPrimitiveSizeInBits();
1018 if (SV->getType()->isFloatingPoint())
1019 SV = new BitCastInst(SV, IntegerType::get(SrcWidth),
1020 SV->getName(), SI);
Chris Lattner5ee4d072007-04-11 15:45:25 +00001021 else if (isa<PointerType>(SV->getType()))
1022 SV = new PtrToIntInst(SV, TD.getIntPtrType(), SV->getName(), SI);
Chris Lattnerdaa012d2007-04-11 00:57:54 +00001023
1024 // Always zero extend the value if needed.
1025 if (SV->getType() != AllocaType)
1026 SV = new ZExtInst(SV, AllocaType, SV->getName(), SI);
1027
1028 // If this is a big-endian system and the store is narrower than the
1029 // full alloca type, we need to do a shift to get the right bits.
1030 int ShAmt = 0;
1031 if (TD.isBigEndian()) {
1032 ShAmt = DestWidth-SrcWidth-Offset;
Chris Lattner3323ce12006-04-14 21:42:41 +00001033 } else {
Chris Lattnerdaa012d2007-04-11 00:57:54 +00001034 ShAmt = Offset;
1035 }
1036
1037 // Note: we support negative bitwidths (with shr) which are not defined.
1038 // We do this to support (f.e.) stores off the end of a structure where
1039 // only some bits in the structure are set.
1040 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1041 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1042 SV = BinaryOperator::createShl(SV,
1043 ConstantInt::get(SV->getType(), ShAmt),
1044 SV->getName(), SI);
1045 Mask <<= ShAmt;
1046 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1047 SV = BinaryOperator::createLShr(SV,
1048 ConstantInt::get(SV->getType(),-ShAmt),
1049 SV->getName(), SI);
1050 Mask = Mask.lshr(ShAmt);
1051 }
1052
1053 // Mask out the bits we are about to insert from the old value, and or
1054 // in the new bits.
1055 if (SrcWidth != DestWidth) {
1056 assert(DestWidth > SrcWidth);
1057 Old = BinaryOperator::createAnd(Old, ConstantInt::get(~Mask),
1058 Old->getName()+".mask", SI);
1059 SV = BinaryOperator::createOr(Old, SV, SV->getName()+".ins", SI);
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001060 }
1061 }
1062 new StoreInst(SV, NewAI, SI);
1063 SI->eraseFromParent();
1064
Chris Lattnerdaa012d2007-04-11 00:57:54 +00001065 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
1066 ConvertUsesToScalar(CI, NewAI, Offset);
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001067 CI->eraseFromParent();
1068 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1069 const PointerType *AggPtrTy =
1070 cast<PointerType>(GEP->getOperand(0)->getType());
1071 const TargetData &TD = getAnalysis<TargetData>();
1072 unsigned AggSizeInBits = TD.getTypeSize(AggPtrTy->getElementType())*8;
1073
1074 // Check to see if this is stepping over an element: GEP Ptr, int C
1075 unsigned NewOffset = Offset;
1076 if (GEP->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001077 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001078 unsigned BitOffset = Idx*AggSizeInBits;
1079
Chris Lattnerdaa012d2007-04-11 00:57:54 +00001080 NewOffset += BitOffset;
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001081 } else if (GEP->getNumOperands() == 3) {
1082 // We know that operand #2 is zero.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001083 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001084 const Type *AggTy = AggPtrTy->getElementType();
1085 if (const SequentialType *SeqTy = dyn_cast<SequentialType>(AggTy)) {
1086 unsigned ElSizeBits = TD.getTypeSize(SeqTy->getElementType())*8;
1087
Chris Lattnerdaa012d2007-04-11 00:57:54 +00001088 NewOffset += ElSizeBits*Idx;
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001089 } else if (const StructType *STy = dyn_cast<StructType>(AggTy)) {
Chris Lattnerc473d8e2007-02-10 19:55:17 +00001090 unsigned EltBitOffset =
1091 TD.getStructLayout(STy)->getElementOffset(Idx)*8;
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001092
Chris Lattnerdaa012d2007-04-11 00:57:54 +00001093 NewOffset += EltBitOffset;
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001094 } else {
1095 assert(0 && "Unsupported operation!");
1096 abort();
1097 }
1098 } else {
1099 assert(0 && "Unsupported operation!");
1100 abort();
1101 }
1102 ConvertUsesToScalar(GEP, NewAI, NewOffset);
1103 GEP->eraseFromParent();
1104 } else {
1105 assert(0 && "Unsupported operation!");
1106 abort();
1107 }
1108 }
1109}