blob: 92d1e2036b7112a6252b0dccb2334c1d3a3b4f0e [file] [log] [blame]
Chris Lattnered7b41e2003-05-27 15:45:27 +00001//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnered7b41e2003-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 Lattner38aec322003-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 Lattnered7b41e2003-05-27 15:45:27 +000019//
20//===----------------------------------------------------------------------===//
21
Chris Lattner0e5f4992006-12-19 21:40:18 +000022#define DEBUG_TYPE "scalarrepl"
Chris Lattnered7b41e2003-05-27 15:45:27 +000023#include "llvm/Transforms/Scalar.h"
Chris Lattner38aec322003-09-11 16:45:55 +000024#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
Chris Lattnered7b41e2003-05-27 15:45:27 +000026#include "llvm/Function.h"
Chris Lattner79b3bd32007-04-25 06:40:51 +000027#include "llvm/GlobalVariable.h"
Misha Brukmand8e1eea2004-07-29 17:05:13 +000028#include "llvm/Instructions.h"
Chris Lattner372dda82007-03-05 07:52:57 +000029#include "llvm/IntrinsicInst.h"
30#include "llvm/Pass.h"
Chris Lattner38aec322003-09-11 16:45:55 +000031#include "llvm/Analysis/Dominators.h"
32#include "llvm/Target/TargetData.h"
33#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Chris Lattner95255282006-06-28 23:17:24 +000034#include "llvm/Support/Debug.h"
Chris Lattnera1888942005-12-12 07:19:13 +000035#include "llvm/Support/GetElementPtrTypeIterator.h"
36#include "llvm/Support/MathExtras.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000037#include "llvm/Support/Compiler.h"
Chris Lattner1ccd1852007-02-12 22:56:41 +000038#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000039#include "llvm/ADT/Statistic.h"
40#include "llvm/ADT/StringExtras.h"
Chris Lattnerd8664732003-12-02 17:43:55 +000041using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000042
Chris Lattner0e5f4992006-12-19 21:40:18 +000043STATISTIC(NumReplaced, "Number of allocas broken up");
44STATISTIC(NumPromoted, "Number of allocas promoted");
45STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattner79b3bd32007-04-25 06:40:51 +000046STATISTIC(NumGlobals, "Number of allocas copied from constant global");
Chris Lattnered7b41e2003-05-27 15:45:27 +000047
Chris Lattner0e5f4992006-12-19 21:40:18 +000048namespace {
Chris Lattner95255282006-06-28 23:17:24 +000049 struct VISIBILITY_HIDDEN SROA : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +000050 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000051 explicit SROA(signed T = -1) : FunctionPass((intptr_t)&ID) {
Devang Patelff366852007-07-09 21:19:23 +000052 if (T == -1)
Chris Lattnerb0e71ed2007-08-02 21:33:36 +000053 SRThreshold = 128;
Devang Patelff366852007-07-09 21:19:23 +000054 else
55 SRThreshold = T;
56 }
Devang Patel794fd752007-05-01 21:15:47 +000057
Chris Lattnered7b41e2003-05-27 15:45:27 +000058 bool runOnFunction(Function &F);
59
Chris Lattner38aec322003-09-11 16:45:55 +000060 bool performScalarRepl(Function &F);
61 bool performPromotion(Function &F);
62
Chris Lattnera15854c2003-08-31 00:45:13 +000063 // getAnalysisUsage - This pass does not require any passes, but we know it
64 // will not alter the CFG, so say so.
65 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patel326821e2007-06-07 21:57:03 +000066 AU.addRequired<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +000067 AU.addRequired<DominanceFrontier>();
68 AU.addRequired<TargetData>();
Chris Lattnera15854c2003-08-31 00:45:13 +000069 AU.setPreservesCFG();
70 }
71
Chris Lattnered7b41e2003-05-27 15:45:27 +000072 private:
Chris Lattner39a1c042007-05-30 06:11:23 +000073 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
74 /// information about the uses. All these fields are initialized to false
75 /// and set to true when something is learned.
76 struct AllocaInfo {
77 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
78 bool isUnsafe : 1;
79
80 /// needsCanon - This is set to true if there is some use of the alloca
81 /// that requires canonicalization.
82 bool needsCanon : 1;
83
84 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
85 bool isMemCpySrc : 1;
86
Zhou Sheng33b0b8d2007-07-06 06:01:16 +000087 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner39a1c042007-05-30 06:11:23 +000088 bool isMemCpyDst : 1;
89
90 AllocaInfo()
91 : isUnsafe(false), needsCanon(false),
92 isMemCpySrc(false), isMemCpyDst(false) {}
93 };
94
Devang Patelff366852007-07-09 21:19:23 +000095 unsigned SRThreshold;
96
Chris Lattner39a1c042007-05-30 06:11:23 +000097 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
98
Chris Lattnerf5990ed2004-11-14 04:24:28 +000099 int isSafeAllocaToScalarRepl(AllocationInst *AI);
Chris Lattner39a1c042007-05-30 06:11:23 +0000100
101 void isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
102 AllocaInfo &Info);
103 void isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
104 AllocaInfo &Info);
105 void isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
106 unsigned OpNo, AllocaInfo &Info);
107 void isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI,
108 AllocaInfo &Info);
109
Chris Lattnera10b29b2007-04-25 05:02:56 +0000110 void DoScalarReplacement(AllocationInst *AI,
111 std::vector<AllocationInst*> &WorkList);
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000112 void CanonicalizeAllocaUsers(AllocationInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000113 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
Chris Lattnera1888942005-12-12 07:19:13 +0000114
Chris Lattner8bf99112007-03-19 00:16:43 +0000115 void RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
Chris Lattner372dda82007-03-05 07:52:57 +0000116 SmallVector<AllocaInst*, 32> &NewElts);
117
Chris Lattnera1888942005-12-12 07:19:13 +0000118 const Type *CanConvertToScalar(Value *V, bool &IsNotTrivial);
119 void ConvertToScalar(AllocationInst *AI, const Type *Ty);
120 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset);
Chris Lattner800de312008-02-29 07:03:13 +0000121 Value *ConvertUsesOfLoadToScalar(LoadInst *LI, AllocaInst *NewAI,
122 unsigned Offset);
123 Value *ConvertUsesOfStoreToScalar(StoreInst *SI, AllocaInst *NewAI,
124 unsigned Offset);
Chris Lattner79b3bd32007-04-25 06:40:51 +0000125 static Instruction *isOnlyCopiedFromConstantGlobal(AllocationInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000126 };
Chris Lattnered7b41e2003-05-27 15:45:27 +0000127}
128
Dan Gohman844731a2008-05-13 00:00:25 +0000129char SROA::ID = 0;
130static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
131
Brian Gaeked0fde302003-11-11 22:41:34 +0000132// Public interface to the ScalarReplAggregates pass
Devang Patelff366852007-07-09 21:19:23 +0000133FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
134 return new SROA(Threshold);
135}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000136
137
Chris Lattnered7b41e2003-05-27 15:45:27 +0000138bool SROA::runOnFunction(Function &F) {
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000139 bool Changed = performPromotion(F);
140 while (1) {
141 bool LocalChange = performScalarRepl(F);
142 if (!LocalChange) break; // No need to repromote if no scalarrepl
143 Changed = true;
144 LocalChange = performPromotion(F);
145 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
146 }
Chris Lattner38aec322003-09-11 16:45:55 +0000147
148 return Changed;
149}
150
151
152bool SROA::performPromotion(Function &F) {
153 std::vector<AllocaInst*> Allocas;
Devang Patel326821e2007-06-07 21:57:03 +0000154 DominatorTree &DT = getAnalysis<DominatorTree>();
Chris Lattner43f820d2003-10-05 21:20:13 +0000155 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
Chris Lattner38aec322003-09-11 16:45:55 +0000156
Chris Lattner02a3be02003-09-20 14:39:18 +0000157 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +0000158
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000159 bool Changed = false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000160
Chris Lattner38aec322003-09-11 16:45:55 +0000161 while (1) {
162 Allocas.clear();
163
164 // Find allocas that are safe to promote, by looking at all instructions in
165 // the entry node
166 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
167 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Devang Patel41968df2007-04-25 17:15:20 +0000168 if (isAllocaPromotable(AI))
Chris Lattner38aec322003-09-11 16:45:55 +0000169 Allocas.push_back(AI);
170
171 if (Allocas.empty()) break;
172
Devang Patel326821e2007-06-07 21:57:03 +0000173 PromoteMemToReg(Allocas, DT, DF);
Chris Lattner38aec322003-09-11 16:45:55 +0000174 NumPromoted += Allocas.size();
175 Changed = true;
176 }
177
178 return Changed;
179}
180
Chris Lattner38aec322003-09-11 16:45:55 +0000181// performScalarRepl - This algorithm is a simple worklist driven algorithm,
182// which runs on all of the malloc/alloca instructions in the function, removing
183// them if they are only used by getelementptr instructions.
184//
185bool SROA::performScalarRepl(Function &F) {
Chris Lattnered7b41e2003-05-27 15:45:27 +0000186 std::vector<AllocationInst*> WorkList;
187
188 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
Chris Lattner02a3be02003-09-20 14:39:18 +0000189 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000190 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
191 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
192 WorkList.push_back(A);
193
Chris Lattner71394062007-05-24 18:43:04 +0000194 const TargetData &TD = getAnalysis<TargetData>();
195
Chris Lattnered7b41e2003-05-27 15:45:27 +0000196 // Process the worklist
197 bool Changed = false;
198 while (!WorkList.empty()) {
199 AllocationInst *AI = WorkList.back();
200 WorkList.pop_back();
Chris Lattnera1888942005-12-12 07:19:13 +0000201
Chris Lattneradd2bd72006-12-22 23:14:42 +0000202 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
203 // with unused elements.
204 if (AI->use_empty()) {
205 AI->eraseFromParent();
206 continue;
207 }
208
Chris Lattnera1888942005-12-12 07:19:13 +0000209 // If we can turn this aggregate value (potentially with casts) into a
210 // simple scalar value that can be mem2reg'd into a register value.
211 bool IsNotTrivial = false;
212 if (const Type *ActualType = CanConvertToScalar(AI, IsNotTrivial))
Chris Lattnerdf4f2262006-04-20 20:48:50 +0000213 if (IsNotTrivial && ActualType != Type::VoidTy) {
Chris Lattnera1888942005-12-12 07:19:13 +0000214 ConvertToScalar(AI, ActualType);
215 Changed = true;
216 continue;
217 }
Chris Lattnered7b41e2003-05-27 15:45:27 +0000218
Chris Lattner79b3bd32007-04-25 06:40:51 +0000219 // Check to see if we can perform the core SROA transformation. We cannot
220 // transform the allocation instruction if it is an array allocation
221 // (allocations OF arrays are ok though), and an allocation of a scalar
222 // value cannot be decomposed at all.
Chris Lattnera10b29b2007-04-25 05:02:56 +0000223 if (!AI->isArrayAllocation() &&
224 (isa<StructType>(AI->getAllocatedType()) ||
Chris Lattner71394062007-05-24 18:43:04 +0000225 isa<ArrayType>(AI->getAllocatedType())) &&
226 AI->getAllocatedType()->isSized() &&
Duncan Sands3cb36502007-11-04 14:43:57 +0000227 TD.getABITypeSize(AI->getAllocatedType()) < SRThreshold) {
Chris Lattnera10b29b2007-04-25 05:02:56 +0000228 // Check that all of the users of the allocation are capable of being
229 // transformed.
230 switch (isSafeAllocaToScalarRepl(AI)) {
231 default: assert(0 && "Unexpected value!");
232 case 0: // Not safe to scalar replace.
233 break;
234 case 1: // Safe, but requires cleanup/canonicalizations first
235 CanonicalizeAllocaUsers(AI);
236 // FALL THROUGH.
237 case 3: // Safe to scalar replace.
238 DoScalarReplacement(AI, WorkList);
239 Changed = true;
Chris Lattner372dda82007-03-05 07:52:57 +0000240 continue;
241 }
Chris Lattnered7b41e2003-05-27 15:45:27 +0000242 }
Chris Lattner79b3bd32007-04-25 06:40:51 +0000243
244 // Check to see if this allocation is only modified by a memcpy/memmove from
245 // a constant global. If this is the case, we can change all users to use
246 // the constant global instead. This is commonly produced by the CFE by
247 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
248 // is only subsequently read.
249 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
250 DOUT << "Found alloca equal to global: " << *AI;
251 DOUT << " memcpy = " << *TheCopy;
252 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
253 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
254 TheCopy->eraseFromParent(); // Don't mutate the global.
255 AI->eraseFromParent();
256 ++NumGlobals;
257 Changed = true;
258 continue;
259 }
Chris Lattnera10b29b2007-04-25 05:02:56 +0000260
261 // Otherwise, couldn't process this.
Chris Lattnered7b41e2003-05-27 15:45:27 +0000262 }
263
264 return Changed;
265}
Chris Lattner5e062a12003-05-30 04:15:41 +0000266
Chris Lattnera10b29b2007-04-25 05:02:56 +0000267/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
268/// predicate, do SROA now.
269void SROA::DoScalarReplacement(AllocationInst *AI,
270 std::vector<AllocationInst*> &WorkList) {
Chris Lattner79b3bd32007-04-25 06:40:51 +0000271 DOUT << "Found inst to SROA: " << *AI;
Chris Lattnera10b29b2007-04-25 05:02:56 +0000272 SmallVector<AllocaInst*, 32> ElementAllocas;
273 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
274 ElementAllocas.reserve(ST->getNumContainedTypes());
275 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
276 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
277 AI->getAlignment(),
278 AI->getName() + "." + utostr(i), AI);
279 ElementAllocas.push_back(NA);
280 WorkList.push_back(NA); // Add to worklist for recursive processing
281 }
282 } else {
283 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
284 ElementAllocas.reserve(AT->getNumElements());
285 const Type *ElTy = AT->getElementType();
286 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
287 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
288 AI->getName() + "." + utostr(i), AI);
289 ElementAllocas.push_back(NA);
290 WorkList.push_back(NA); // Add to worklist for recursive processing
291 }
292 }
293
294 // Now that we have created the alloca instructions that we want to use,
295 // expand the getelementptr instructions to use them.
296 //
297 while (!AI->use_empty()) {
298 Instruction *User = cast<Instruction>(AI->use_back());
299 if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
300 RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
301 BCInst->eraseFromParent();
302 continue;
303 }
304
Matthijs Kooijman02518142008-06-05 12:51:53 +0000305 // Replace %res = load { i32, i32 }* %alloc
306 // by
307 // %load.0 = load i32* %alloc.0
308 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
309 // %load.1 = load i32* %alloc.1
310 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
311 // (Also works for arrays instead of structs)
312 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
313 Value *Insert = UndefValue::get(LI->getType());
314 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
315 Value *Load = new LoadInst(ElementAllocas[i], "load", LI);
316 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
317 }
318 LI->replaceAllUsesWith(Insert);
319 LI->eraseFromParent();
320 continue;
321 }
322
323 // Replace store { i32, i32 } %val, { i32, i32 }* %alloc
324 // by
325 // %val.0 = extractvalue { i32, i32 } %val, 0
326 // store i32 %val.0, i32* %alloc.0
327 // %val.1 = extractvalue { i32, i32 } %val, 1
328 // store i32 %val.1, i32* %alloc.1
329 // (Also works for arrays instead of structs)
330 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
331 Value *Val = SI->getOperand(0);
332 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
333 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
334 new StoreInst(Extract, ElementAllocas[i], SI);
335 }
336 SI->eraseFromParent();
337 continue;
338 }
339
Chris Lattnera10b29b2007-04-25 05:02:56 +0000340 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
341 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
342 unsigned Idx =
343 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
344
345 assert(Idx < ElementAllocas.size() && "Index out of range?");
346 AllocaInst *AllocaToUse = ElementAllocas[Idx];
347
348 Value *RepValue;
349 if (GEPI->getNumOperands() == 3) {
350 // Do not insert a new getelementptr instruction with zero indices, only
351 // to have it optimized out later.
352 RepValue = AllocaToUse;
353 } else {
354 // We are indexing deeply into the structure, so we still need a
355 // getelement ptr instruction to finish the indexing. This may be
356 // expanded itself once the worklist is rerun.
357 //
358 SmallVector<Value*, 8> NewArgs;
359 NewArgs.push_back(Constant::getNullValue(Type::Int32Ty));
360 NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
Gabor Greif051a9502008-04-06 20:25:17 +0000361 RepValue = GetElementPtrInst::Create(AllocaToUse, NewArgs.begin(),
362 NewArgs.end(), "", GEPI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000363 RepValue->takeName(GEPI);
364 }
365
366 // If this GEP is to the start of the aggregate, check for memcpys.
367 if (Idx == 0) {
368 bool IsStartOfAggregateGEP = true;
369 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i) {
370 if (!isa<ConstantInt>(GEPI->getOperand(i))) {
371 IsStartOfAggregateGEP = false;
372 break;
373 }
374 if (!cast<ConstantInt>(GEPI->getOperand(i))->isZero()) {
375 IsStartOfAggregateGEP = false;
376 break;
377 }
378 }
379
380 if (IsStartOfAggregateGEP)
381 RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas);
382 }
383
384
385 // Move all of the users over to the new GEP.
386 GEPI->replaceAllUsesWith(RepValue);
387 // Delete the old GEP
388 GEPI->eraseFromParent();
389 }
390
391 // Finally, delete the Alloca instruction
392 AI->eraseFromParent();
393 NumReplaced++;
394}
395
Chris Lattner5e062a12003-05-30 04:15:41 +0000396
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000397/// isSafeElementUse - Check to see if this use is an allowed use for a
Chris Lattner8bf99112007-03-19 00:16:43 +0000398/// getelementptr instruction of an array aggregate allocation. isFirstElt
399/// indicates whether Ptr is known to the start of the aggregate.
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000400///
Chris Lattner39a1c042007-05-30 06:11:23 +0000401void SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
402 AllocaInfo &Info) {
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000403 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
404 I != E; ++I) {
405 Instruction *User = cast<Instruction>(*I);
406 switch (User->getOpcode()) {
407 case Instruction::Load: break;
408 case Instruction::Store:
409 // Store is ok if storing INTO the pointer, not storing the pointer
Chris Lattner39a1c042007-05-30 06:11:23 +0000410 if (User->getOperand(0) == Ptr) return MarkUnsafe(Info);
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000411 break;
412 case Instruction::GetElementPtr: {
413 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
Chris Lattner8bf99112007-03-19 00:16:43 +0000414 bool AreAllZeroIndices = isFirstElt;
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000415 if (GEP->getNumOperands() > 1) {
Chris Lattner8bf99112007-03-19 00:16:43 +0000416 if (!isa<ConstantInt>(GEP->getOperand(1)) ||
417 !cast<ConstantInt>(GEP->getOperand(1))->isZero())
Chris Lattner39a1c042007-05-30 06:11:23 +0000418 // Using pointer arithmetic to navigate the array.
419 return MarkUnsafe(Info);
Chris Lattner8bf99112007-03-19 00:16:43 +0000420
421 if (AreAllZeroIndices) {
422 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) {
423 if (!isa<ConstantInt>(GEP->getOperand(i)) ||
424 !cast<ConstantInt>(GEP->getOperand(i))->isZero()) {
425 AreAllZeroIndices = false;
426 break;
427 }
428 }
429 }
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000430 }
Chris Lattner39a1c042007-05-30 06:11:23 +0000431 isSafeElementUse(GEP, AreAllZeroIndices, AI, Info);
432 if (Info.isUnsafe) return;
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000433 break;
434 }
Chris Lattner8bf99112007-03-19 00:16:43 +0000435 case Instruction::BitCast:
Chris Lattner39a1c042007-05-30 06:11:23 +0000436 if (isFirstElt) {
437 isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI, Info);
438 if (Info.isUnsafe) return;
Chris Lattner8bf99112007-03-19 00:16:43 +0000439 break;
Chris Lattner8bf99112007-03-19 00:16:43 +0000440 }
441 DOUT << " Transformation preventing inst: " << *User;
Chris Lattner39a1c042007-05-30 06:11:23 +0000442 return MarkUnsafe(Info);
443 case Instruction::Call:
444 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
445 if (isFirstElt) {
446 isSafeMemIntrinsicOnAllocation(MI, AI, I.getOperandNo(), Info);
447 if (Info.isUnsafe) return;
448 break;
449 }
450 }
451 DOUT << " Transformation preventing inst: " << *User;
452 return MarkUnsafe(Info);
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000453 default:
Bill Wendlingb7427032006-11-26 09:46:52 +0000454 DOUT << " Transformation preventing inst: " << *User;
Chris Lattner39a1c042007-05-30 06:11:23 +0000455 return MarkUnsafe(Info);
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000456 }
457 }
Chris Lattner39a1c042007-05-30 06:11:23 +0000458 return; // All users look ok :)
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000459}
460
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000461/// AllUsersAreLoads - Return true if all users of this value are loads.
462static bool AllUsersAreLoads(Value *Ptr) {
463 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
464 I != E; ++I)
465 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
466 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000467 return true;
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000468}
469
Chris Lattner5e062a12003-05-30 04:15:41 +0000470/// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
471/// aggregate allocation.
472///
Chris Lattner39a1c042007-05-30 06:11:23 +0000473void SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
474 AllocaInfo &Info) {
Chris Lattner372dda82007-03-05 07:52:57 +0000475 if (BitCastInst *C = dyn_cast<BitCastInst>(User))
Chris Lattner39a1c042007-05-30 06:11:23 +0000476 return isSafeUseOfBitCastedAllocation(C, AI, Info);
Chris Lattnerbe883a22003-11-25 21:09:18 +0000477
Matthijs Kooijman02518142008-06-05 12:51:53 +0000478 if (isa<LoadInst>(User))
479 return; // Loads (returning a first class aggregrate) are always rewritable
480
481 if (isa<StoreInst>(User) && User->getOperand(0) != AI)
482 return; // Store is ok if storing INTO the pointer, not storing the pointer
483
Chris Lattner39a1c042007-05-30 06:11:23 +0000484 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User);
485 if (GEPI == 0)
486 return MarkUnsafe(Info);
487
Chris Lattnerbe883a22003-11-25 21:09:18 +0000488 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
489
Chris Lattner25de4862006-03-08 01:05:29 +0000490 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
Chris Lattnerbe883a22003-11-25 21:09:18 +0000491 if (I == E ||
Chris Lattner39a1c042007-05-30 06:11:23 +0000492 I.getOperand() != Constant::getNullValue(I.getOperand()->getType())) {
493 return MarkUnsafe(Info);
494 }
Chris Lattnerbe883a22003-11-25 21:09:18 +0000495
496 ++I;
Chris Lattner39a1c042007-05-30 06:11:23 +0000497 if (I == E) return MarkUnsafe(Info); // ran out of GEP indices??
Chris Lattnerbe883a22003-11-25 21:09:18 +0000498
Chris Lattner8bf99112007-03-19 00:16:43 +0000499 bool IsAllZeroIndices = true;
500
Chris Lattnerbe883a22003-11-25 21:09:18 +0000501 // If this is a use of an array allocation, do a bit more checking for sanity.
502 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
503 uint64_t NumElements = AT->getNumElements();
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000504
Chris Lattner8bf99112007-03-19 00:16:43 +0000505 if (ConstantInt *Idx = dyn_cast<ConstantInt>(I.getOperand())) {
506 IsAllZeroIndices &= Idx->isZero();
507
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000508 // Check to make sure that index falls within the array. If not,
509 // something funny is going on, so we won't do the optimization.
510 //
Chris Lattner8bf99112007-03-19 00:16:43 +0000511 if (Idx->getZExtValue() >= NumElements)
Chris Lattner39a1c042007-05-30 06:11:23 +0000512 return MarkUnsafe(Info);
Misha Brukmanfd939082005-04-21 23:48:37 +0000513
Chris Lattner25de4862006-03-08 01:05:29 +0000514 // We cannot scalar repl this level of the array unless any array
515 // sub-indices are in-range constants. In particular, consider:
516 // A[0][i]. We cannot know that the user isn't doing invalid things like
517 // allowing i to index an out-of-range subscript that accesses A[1].
518 //
519 // Scalar replacing *just* the outer index of the array is probably not
520 // going to be a win anyway, so just give up.
Reid Spencer9d6565a2007-02-15 02:26:10 +0000521 for (++I; I != E && (isa<ArrayType>(*I) || isa<VectorType>(*I)); ++I) {
Chris Lattnerd9251502006-11-07 22:42:47 +0000522 uint64_t NumElements;
523 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*I))
524 NumElements = SubArrayTy->getNumElements();
525 else
Reid Spencer9d6565a2007-02-15 02:26:10 +0000526 NumElements = cast<VectorType>(*I)->getNumElements();
Chris Lattnerd9251502006-11-07 22:42:47 +0000527
Chris Lattner8bf99112007-03-19 00:16:43 +0000528 ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
Chris Lattner39a1c042007-05-30 06:11:23 +0000529 if (!IdxVal) return MarkUnsafe(Info);
Chris Lattner8bf99112007-03-19 00:16:43 +0000530 if (IdxVal->getZExtValue() >= NumElements)
Chris Lattner39a1c042007-05-30 06:11:23 +0000531 return MarkUnsafe(Info);
Chris Lattner8bf99112007-03-19 00:16:43 +0000532 IsAllZeroIndices &= IdxVal->isZero();
Chris Lattner25de4862006-03-08 01:05:29 +0000533 }
534
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000535 } else {
Chris Lattner8bf99112007-03-19 00:16:43 +0000536 IsAllZeroIndices = 0;
537
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000538 // If this is an array index and the index is not constant, we cannot
539 // promote... that is unless the array has exactly one or two elements in
540 // it, in which case we CAN promote it, but we have to canonicalize this
541 // out if this is the only problem.
Chris Lattner25de4862006-03-08 01:05:29 +0000542 if ((NumElements == 1 || NumElements == 2) &&
Chris Lattner39a1c042007-05-30 06:11:23 +0000543 AllUsersAreLoads(GEPI)) {
544 Info.needsCanon = true;
545 return; // Canonicalization required!
546 }
547 return MarkUnsafe(Info);
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000548 }
Chris Lattner5e062a12003-05-30 04:15:41 +0000549 }
Chris Lattnerbe883a22003-11-25 21:09:18 +0000550
551 // If there are any non-simple uses of this getelementptr, make sure to reject
552 // them.
Chris Lattner39a1c042007-05-30 06:11:23 +0000553 return isSafeElementUse(GEPI, IsAllZeroIndices, AI, Info);
Chris Lattner8bf99112007-03-19 00:16:43 +0000554}
555
556/// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
557/// intrinsic can be promoted by SROA. At this point, we know that the operand
558/// of the memintrinsic is a pointer to the beginning of the allocation.
Chris Lattner39a1c042007-05-30 06:11:23 +0000559void SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
560 unsigned OpNo, AllocaInfo &Info) {
Chris Lattner8bf99112007-03-19 00:16:43 +0000561 // If not constant length, give up.
562 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
Chris Lattner39a1c042007-05-30 06:11:23 +0000563 if (!Length) return MarkUnsafe(Info);
Chris Lattner8bf99112007-03-19 00:16:43 +0000564
565 // If not the whole aggregate, give up.
566 const TargetData &TD = getAnalysis<TargetData>();
Duncan Sands3cb36502007-11-04 14:43:57 +0000567 if (Length->getZExtValue() !=
568 TD.getABITypeSize(AI->getType()->getElementType()))
Chris Lattner39a1c042007-05-30 06:11:23 +0000569 return MarkUnsafe(Info);
Chris Lattner8bf99112007-03-19 00:16:43 +0000570
571 // We only know about memcpy/memset/memmove.
572 if (!isa<MemCpyInst>(MI) && !isa<MemSetInst>(MI) && !isa<MemMoveInst>(MI))
Chris Lattner39a1c042007-05-30 06:11:23 +0000573 return MarkUnsafe(Info);
574
575 // Otherwise, we can transform it. Determine whether this is a memcpy/set
576 // into or out of the aggregate.
577 if (OpNo == 1)
578 Info.isMemCpyDst = true;
579 else {
580 assert(OpNo == 2);
581 Info.isMemCpySrc = true;
582 }
Chris Lattner5e062a12003-05-30 04:15:41 +0000583}
584
Chris Lattner372dda82007-03-05 07:52:57 +0000585/// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
586/// are
Chris Lattner39a1c042007-05-30 06:11:23 +0000587void SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI,
588 AllocaInfo &Info) {
Chris Lattner372dda82007-03-05 07:52:57 +0000589 for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
590 UI != E; ++UI) {
591 if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
Chris Lattner39a1c042007-05-30 06:11:23 +0000592 isSafeUseOfBitCastedAllocation(BCU, AI, Info);
Chris Lattner372dda82007-03-05 07:52:57 +0000593 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
Chris Lattner39a1c042007-05-30 06:11:23 +0000594 isSafeMemIntrinsicOnAllocation(MI, AI, UI.getOperandNo(), Info);
Chris Lattner372dda82007-03-05 07:52:57 +0000595 } else {
Chris Lattner39a1c042007-05-30 06:11:23 +0000596 return MarkUnsafe(Info);
Chris Lattner372dda82007-03-05 07:52:57 +0000597 }
Chris Lattner39a1c042007-05-30 06:11:23 +0000598 if (Info.isUnsafe) return;
Chris Lattner372dda82007-03-05 07:52:57 +0000599 }
Chris Lattner372dda82007-03-05 07:52:57 +0000600}
601
Chris Lattner8bf99112007-03-19 00:16:43 +0000602/// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
603/// to its first element. Transform users of the cast to use the new values
604/// instead.
605void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
Chris Lattner372dda82007-03-05 07:52:57 +0000606 SmallVector<AllocaInst*, 32> &NewElts) {
607 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
608 const TargetData &TD = getAnalysis<TargetData>();
Chris Lattner8bf99112007-03-19 00:16:43 +0000609
610 Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
611 while (UI != UE) {
612 if (BitCastInst *BCU = dyn_cast<BitCastInst>(*UI)) {
Chris Lattner372dda82007-03-05 07:52:57 +0000613 RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
Chris Lattner8bf99112007-03-19 00:16:43 +0000614 ++UI;
615 BCU->eraseFromParent();
Chris Lattner372dda82007-03-05 07:52:57 +0000616 continue;
617 }
618
619 // Otherwise, must be memcpy/memmove/memset of the entire aggregate. Split
620 // into one per element.
Chris Lattner8bf99112007-03-19 00:16:43 +0000621 MemIntrinsic *MI = dyn_cast<MemIntrinsic>(*UI);
622
623 // If it's not a mem intrinsic, it must be some other user of a gep of the
624 // first pointer. Just leave these alone.
625 if (!MI) {
626 ++UI;
627 continue;
628 }
Chris Lattner372dda82007-03-05 07:52:57 +0000629
630 // If this is a memcpy/memmove, construct the other pointer as the
631 // appropriate type.
632 Value *OtherPtr = 0;
633 if (MemCpyInst *MCI = dyn_cast<MemCpyInst>(MI)) {
634 if (BCInst == MCI->getRawDest())
635 OtherPtr = MCI->getRawSource();
636 else {
637 assert(BCInst == MCI->getRawSource());
638 OtherPtr = MCI->getRawDest();
639 }
640 } else if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
641 if (BCInst == MMI->getRawDest())
642 OtherPtr = MMI->getRawSource();
643 else {
644 assert(BCInst == MMI->getRawSource());
645 OtherPtr = MMI->getRawDest();
646 }
647 }
648
649 // If there is an other pointer, we want to convert it to the same pointer
650 // type as AI has, so we can GEP through it.
651 if (OtherPtr) {
652 // It is likely that OtherPtr is a bitcast, if so, remove it.
653 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
654 OtherPtr = BC->getOperand(0);
655 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
656 if (BCE->getOpcode() == Instruction::BitCast)
657 OtherPtr = BCE->getOperand(0);
658
659 // If the pointer is not the right type, insert a bitcast to the right
660 // type.
661 if (OtherPtr->getType() != AI->getType())
662 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
663 MI);
664 }
665
666 // Process each element of the aggregate.
667 Value *TheFn = MI->getOperand(0);
668 const Type *BytePtrTy = MI->getRawDest()->getType();
669 bool SROADest = MI->getRawDest() == BCInst;
670
671 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
672 // If this is a memcpy/memmove, emit a GEP of the other element address.
673 Value *OtherElt = 0;
674 if (OtherPtr) {
David Greeneb8f74792007-09-04 15:46:09 +0000675 Value *Idx[2];
676 Idx[0] = Zero;
677 Idx[1] = ConstantInt::get(Type::Int32Ty, i);
Gabor Greif051a9502008-04-06 20:25:17 +0000678 OtherElt = GetElementPtrInst::Create(OtherPtr, Idx, Idx + 2,
679 OtherPtr->getNameStr()+"."+utostr(i),
680 MI);
Chris Lattner372dda82007-03-05 07:52:57 +0000681 }
682
683 Value *EltPtr = NewElts[i];
Chris Lattnerc14d3ca2007-03-08 06:36:54 +0000684 const Type *EltTy =cast<PointerType>(EltPtr->getType())->getElementType();
685
686 // If we got down to a scalar, insert a load or store as appropriate.
Dan Gohman31e5bdc2008-05-23 00:12:03 +0000687 if (EltTy->isSingleValueType()) {
Chris Lattnerc14d3ca2007-03-08 06:36:54 +0000688 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
689 Value *Elt = new LoadInst(SROADest ? OtherElt : EltPtr, "tmp",
690 MI);
691 new StoreInst(Elt, SROADest ? EltPtr : OtherElt, MI);
692 continue;
693 } else {
694 assert(isa<MemSetInst>(MI));
695
696 // If the stored element is zero (common case), just store a null
697 // constant.
698 Constant *StoreVal;
699 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
700 if (CI->isZero()) {
701 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
702 } else {
Dan Gohman07a96762007-07-16 14:29:03 +0000703 // If EltTy is a vector type, get the element type.
Chris Lattnerc14d3ca2007-03-08 06:36:54 +0000704 const Type *ValTy = EltTy;
705 if (const VectorType *VTy = dyn_cast<VectorType>(ValTy))
706 ValTy = VTy->getElementType();
Duncan Sands3cb36502007-11-04 14:43:57 +0000707
Chris Lattnerc14d3ca2007-03-08 06:36:54 +0000708 // Construct an integer with the right value.
Duncan Sands3cb36502007-11-04 14:43:57 +0000709 unsigned EltSize = TD.getTypeSizeInBits(ValTy);
710 APInt OneVal(EltSize, CI->getZExtValue());
Chris Lattnerc14d3ca2007-03-08 06:36:54 +0000711 APInt TotalVal(OneVal);
712 // Set each byte.
Duncan Sands3cb36502007-11-04 14:43:57 +0000713 for (unsigned i = 0; 8*i < EltSize; ++i) {
Chris Lattnerc14d3ca2007-03-08 06:36:54 +0000714 TotalVal = TotalVal.shl(8);
715 TotalVal |= OneVal;
716 }
Duncan Sands3cb36502007-11-04 14:43:57 +0000717
Chris Lattnerc14d3ca2007-03-08 06:36:54 +0000718 // Convert the integer value to the appropriate type.
719 StoreVal = ConstantInt::get(TotalVal);
720 if (isa<PointerType>(ValTy))
721 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
722 else if (ValTy->isFloatingPoint())
723 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
724 assert(StoreVal->getType() == ValTy && "Type mismatch!");
725
726 // If the requested value was a vector constant, create it.
727 if (EltTy != ValTy) {
728 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
729 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
730 StoreVal = ConstantVector::get(&Elts[0], NumElts);
731 }
732 }
733 new StoreInst(StoreVal, EltPtr, MI);
734 continue;
735 }
736 // Otherwise, if we're storing a byte variable, use a memset call for
737 // this element.
738 }
739 }
Chris Lattner372dda82007-03-05 07:52:57 +0000740
741 // Cast the element pointer to BytePtrTy.
742 if (EltPtr->getType() != BytePtrTy)
743 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +0000744
745 // Cast the other pointer (if we have one) to BytePtrTy.
746 if (OtherElt && OtherElt->getType() != BytePtrTy)
747 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
748 MI);
749
Duncan Sands3cb36502007-11-04 14:43:57 +0000750 unsigned EltSize = TD.getABITypeSize(EltTy);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +0000751
Chris Lattner372dda82007-03-05 07:52:57 +0000752 // Finally, insert the meminst for this element.
753 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
754 Value *Ops[] = {
755 SROADest ? EltPtr : OtherElt, // Dest ptr
756 SROADest ? OtherElt : EltPtr, // Src ptr
757 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
758 Zero // Align
759 };
Gabor Greif051a9502008-04-06 20:25:17 +0000760 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +0000761 } else {
762 assert(isa<MemSetInst>(MI));
Chris Lattner372dda82007-03-05 07:52:57 +0000763 Value *Ops[] = {
764 EltPtr, MI->getOperand(2), // Dest, Value,
765 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
766 Zero // Align
767 };
Gabor Greif051a9502008-04-06 20:25:17 +0000768 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
Chris Lattner372dda82007-03-05 07:52:57 +0000769 }
Chris Lattnerc14d3ca2007-03-08 06:36:54 +0000770 }
Chris Lattner372dda82007-03-05 07:52:57 +0000771
772 // Finally, MI is now dead, as we've modified its actions to occur on all of
773 // the elements of the aggregate.
Chris Lattner8bf99112007-03-19 00:16:43 +0000774 ++UI;
Chris Lattner372dda82007-03-05 07:52:57 +0000775 MI->eraseFromParent();
776 }
Chris Lattner372dda82007-03-05 07:52:57 +0000777}
778
Duncan Sands3cb36502007-11-04 14:43:57 +0000779/// HasPadding - Return true if the specified type has any structure or
780/// alignment padding, false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +0000781static bool HasPadding(const Type *Ty, const TargetData &TD) {
Chris Lattner39a1c042007-05-30 06:11:23 +0000782 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
783 const StructLayout *SL = TD.getStructLayout(STy);
784 unsigned PrevFieldBitOffset = 0;
785 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan Sands3cb36502007-11-04 14:43:57 +0000786 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
787
Chris Lattner39a1c042007-05-30 06:11:23 +0000788 // Padding in sub-elements?
Duncan Sandsa0fcc082008-06-04 08:21:45 +0000789 if (HasPadding(STy->getElementType(i), TD))
Chris Lattner39a1c042007-05-30 06:11:23 +0000790 return true;
Duncan Sands3cb36502007-11-04 14:43:57 +0000791
Chris Lattner39a1c042007-05-30 06:11:23 +0000792 // Check to see if there is any padding between this element and the
793 // previous one.
794 if (i) {
Duncan Sands3cb36502007-11-04 14:43:57 +0000795 unsigned PrevFieldEnd =
Chris Lattner39a1c042007-05-30 06:11:23 +0000796 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
797 if (PrevFieldEnd < FieldBitOffset)
798 return true;
799 }
Duncan Sands3cb36502007-11-04 14:43:57 +0000800
Chris Lattner39a1c042007-05-30 06:11:23 +0000801 PrevFieldBitOffset = FieldBitOffset;
802 }
Duncan Sands3cb36502007-11-04 14:43:57 +0000803
Chris Lattner39a1c042007-05-30 06:11:23 +0000804 // Check for tail padding.
805 if (unsigned EltCount = STy->getNumElements()) {
806 unsigned PrevFieldEnd = PrevFieldBitOffset +
807 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
Duncan Sands3cb36502007-11-04 14:43:57 +0000808 if (PrevFieldEnd < SL->getSizeInBits())
Chris Lattner39a1c042007-05-30 06:11:23 +0000809 return true;
810 }
811
812 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +0000813 return HasPadding(ATy->getElementType(), TD);
Duncan Sands3cb36502007-11-04 14:43:57 +0000814 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +0000815 return HasPadding(VTy->getElementType(), TD);
Chris Lattner39a1c042007-05-30 06:11:23 +0000816 }
Duncan Sandsa0fcc082008-06-04 08:21:45 +0000817 return TD.getTypeSizeInBits(Ty) != TD.getABITypeSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +0000818}
Chris Lattner372dda82007-03-05 07:52:57 +0000819
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000820/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
821/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
822/// or 1 if safe after canonicalization has been performed.
Chris Lattner5e062a12003-05-30 04:15:41 +0000823///
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000824int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +0000825 // Loop over the use list of the alloca. We can only transform it if all of
826 // the users are safe to transform.
Chris Lattner39a1c042007-05-30 06:11:23 +0000827 AllocaInfo Info;
828
Chris Lattner5e062a12003-05-30 04:15:41 +0000829 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000830 I != E; ++I) {
Chris Lattner39a1c042007-05-30 06:11:23 +0000831 isSafeUseOfAllocation(cast<Instruction>(*I), AI, Info);
832 if (Info.isUnsafe) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000833 DOUT << "Cannot transform: " << *AI << " due to user: " << **I;
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000834 return 0;
Chris Lattner5e062a12003-05-30 04:15:41 +0000835 }
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000836 }
Chris Lattner39a1c042007-05-30 06:11:23 +0000837
838 // Okay, we know all the users are promotable. If the aggregate is a memcpy
839 // source and destination, we have to be careful. In particular, the memcpy
840 // could be moving around elements that live in structure padding of the LLVM
841 // types, but may actually be used. In these cases, we refuse to promote the
842 // struct.
843 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Duncan Sands3cb36502007-11-04 14:43:57 +0000844 HasPadding(AI->getType()->getElementType(), getAnalysis<TargetData>()))
Chris Lattner39a1c042007-05-30 06:11:23 +0000845 return 0;
Duncan Sands3cb36502007-11-04 14:43:57 +0000846
Chris Lattner39a1c042007-05-30 06:11:23 +0000847 // If we require cleanup, return 1, otherwise return 3.
848 return Info.needsCanon ? 1 : 3;
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000849}
850
851/// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified
852/// allocation, but only if cleaned up, perform the cleanups required.
853void SROA::CanonicalizeAllocaUsers(AllocationInst *AI) {
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000854 // At this point, we know that the end result will be SROA'd and promoted, so
855 // we can insert ugly code if required so long as sroa+mem2reg will clean it
856 // up.
857 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
858 UI != E; ) {
Chris Lattnera9d1a842007-03-19 18:25:57 +0000859 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI++);
860 if (!GEPI) continue;
Reid Spencer96326f92004-11-15 17:29:41 +0000861 gep_type_iterator I = gep_type_begin(GEPI);
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000862 ++I;
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000863
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000864 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
865 uint64_t NumElements = AT->getNumElements();
Misha Brukmanfd939082005-04-21 23:48:37 +0000866
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000867 if (!isa<ConstantInt>(I.getOperand())) {
868 if (NumElements == 1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +0000869 GEPI->setOperand(2, Constant::getNullValue(Type::Int32Ty));
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000870 } else {
871 assert(NumElements == 2 && "Unhandled case!");
872 // All users of the GEP must be loads. At each use of the GEP, insert
873 // two loads of the appropriate indexed GEP and select between them.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000874 Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(),
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000875 Constant::getNullValue(I.getOperand()->getType()),
Reid Spencere4d87aa2006-12-23 06:05:41 +0000876 "isone", GEPI);
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000877 // Insert the new GEP instructions, which are properly indexed.
Chris Lattner1ccd1852007-02-12 22:56:41 +0000878 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
Reid Spencerc5b206b2006-12-31 05:48:39 +0000879 Indices[1] = Constant::getNullValue(Type::Int32Ty);
Gabor Greif051a9502008-04-06 20:25:17 +0000880 Value *ZeroIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
881 Indices.begin(),
882 Indices.end(),
883 GEPI->getName()+".0", GEPI);
Reid Spencerc5b206b2006-12-31 05:48:39 +0000884 Indices[1] = ConstantInt::get(Type::Int32Ty, 1);
Gabor Greif051a9502008-04-06 20:25:17 +0000885 Value *OneIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
886 Indices.begin(),
887 Indices.end(),
888 GEPI->getName()+".1", GEPI);
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000889 // Replace all loads of the variable index GEP with loads from both
890 // indexes and a select.
891 while (!GEPI->use_empty()) {
892 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
893 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
894 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
Gabor Greif051a9502008-04-06 20:25:17 +0000895 Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI);
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000896 LI->replaceAllUsesWith(R);
897 LI->eraseFromParent();
898 }
899 GEPI->eraseFromParent();
900 }
901 }
902 }
903 }
Chris Lattner5e062a12003-05-30 04:15:41 +0000904}
Chris Lattnera1888942005-12-12 07:19:13 +0000905
906/// MergeInType - Add the 'In' type to the accumulated type so far. If the
907/// types are incompatible, return true, otherwise update Accum and return
908/// false.
Chris Lattnerde6df882006-04-14 21:42:41 +0000909///
Chris Lattnerd22dbdf2006-12-15 07:32:38 +0000910/// There are three cases we handle here:
911/// 1) An effectively-integer union, where the pieces are stored into as
Chris Lattnerde6df882006-04-14 21:42:41 +0000912/// smaller integers (common with byte swap and other idioms).
Chris Lattnerd22dbdf2006-12-15 07:32:38 +0000913/// 2) A union of vector types of the same size and potentially its elements.
914/// Here we turn element accesses into insert/extract element operations.
915/// 3) A union of scalar types, such as int/float or int/pointer. Here we
916/// merge together into integers, allowing the xform to work with #1 as
917/// well.
Chris Lattner5b121cc2006-10-08 23:28:04 +0000918static bool MergeInType(const Type *In, const Type *&Accum,
919 const TargetData &TD) {
Chris Lattnera1888942005-12-12 07:19:13 +0000920 // If this is our first type, just use it.
Reid Spencer9d6565a2007-02-15 02:26:10 +0000921 const VectorType *PTy;
Chris Lattnerde6df882006-04-14 21:42:41 +0000922 if (Accum == Type::VoidTy || In == Accum) {
Chris Lattnera1888942005-12-12 07:19:13 +0000923 Accum = In;
Chris Lattnerd22dbdf2006-12-15 07:32:38 +0000924 } else if (In == Type::VoidTy) {
925 // Noop.
Chris Lattner42a75512007-01-15 02:27:26 +0000926 } else if (In->isInteger() && Accum->isInteger()) { // integer union.
Chris Lattnera1888942005-12-12 07:19:13 +0000927 // Otherwise pick whichever type is larger.
Reid Spencera54b7cb2007-01-12 07:05:14 +0000928 if (cast<IntegerType>(In)->getBitWidth() >
929 cast<IntegerType>(Accum)->getBitWidth())
Chris Lattnera1888942005-12-12 07:19:13 +0000930 Accum = In;
Chris Lattner5b121cc2006-10-08 23:28:04 +0000931 } else if (isa<PointerType>(In) && isa<PointerType>(Accum)) {
Chris Lattnerc8363332006-10-08 23:53:04 +0000932 // Pointer unions just stay as one of the pointers.
Reid Spencer9d6565a2007-02-15 02:26:10 +0000933 } else if (isa<VectorType>(In) || isa<VectorType>(Accum)) {
934 if ((PTy = dyn_cast<VectorType>(Accum)) &&
Chris Lattnerd22dbdf2006-12-15 07:32:38 +0000935 PTy->getElementType() == In) {
936 // Accum is a vector, and we are accessing an element: ok.
Reid Spencer9d6565a2007-02-15 02:26:10 +0000937 } else if ((PTy = dyn_cast<VectorType>(In)) &&
Chris Lattnerd22dbdf2006-12-15 07:32:38 +0000938 PTy->getElementType() == Accum) {
939 // In is a vector, and accum is an element: ok, remember In.
940 Accum = In;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000941 } else if ((PTy = dyn_cast<VectorType>(In)) && isa<VectorType>(Accum) &&
942 PTy->getBitWidth() == cast<VectorType>(Accum)->getBitWidth()) {
Chris Lattnerd22dbdf2006-12-15 07:32:38 +0000943 // Two vectors of the same size: keep Accum.
944 } else {
945 // Cannot insert an short into a <4 x int> or handle
946 // <2 x int> -> <4 x int>
947 return true;
948 }
Chris Lattner21c362d2006-12-13 02:26:45 +0000949 } else {
Chris Lattnerd22dbdf2006-12-15 07:32:38 +0000950 // Pointer/FP/Integer unions merge together as integers.
951 switch (Accum->getTypeID()) {
952 case Type::PointerTyID: Accum = TD.getIntPtrType(); break;
Reid Spencerc5b206b2006-12-31 05:48:39 +0000953 case Type::FloatTyID: Accum = Type::Int32Ty; break;
954 case Type::DoubleTyID: Accum = Type::Int64Ty; break;
Dale Johannesenef0ab932007-09-28 00:21:38 +0000955 case Type::X86_FP80TyID: return true;
956 case Type::FP128TyID: return true;
957 case Type::PPC_FP128TyID: return true;
Chris Lattnerd22dbdf2006-12-15 07:32:38 +0000958 default:
Chris Lattner42a75512007-01-15 02:27:26 +0000959 assert(Accum->isInteger() && "Unknown FP type!");
Chris Lattnerd22dbdf2006-12-15 07:32:38 +0000960 break;
961 }
962
963 switch (In->getTypeID()) {
964 case Type::PointerTyID: In = TD.getIntPtrType(); break;
Reid Spencerc5b206b2006-12-31 05:48:39 +0000965 case Type::FloatTyID: In = Type::Int32Ty; break;
966 case Type::DoubleTyID: In = Type::Int64Ty; break;
Dale Johannesenef0ab932007-09-28 00:21:38 +0000967 case Type::X86_FP80TyID: return true;
968 case Type::FP128TyID: return true;
969 case Type::PPC_FP128TyID: return true;
Chris Lattnerd22dbdf2006-12-15 07:32:38 +0000970 default:
Chris Lattner42a75512007-01-15 02:27:26 +0000971 assert(In->isInteger() && "Unknown FP type!");
Chris Lattnerd22dbdf2006-12-15 07:32:38 +0000972 break;
973 }
974 return MergeInType(In, Accum, TD);
Chris Lattnera1888942005-12-12 07:19:13 +0000975 }
976 return false;
977}
978
Duncan Sands3cb36502007-11-04 14:43:57 +0000979/// getUIntAtLeastAsBigAs - Return an unsigned integer type that is at least
Chris Lattnera1888942005-12-12 07:19:13 +0000980/// as big as the specified type. If there is no suitable type, this returns
981/// null.
Duncan Sands3cb36502007-11-04 14:43:57 +0000982const Type *getUIntAtLeastAsBigAs(unsigned NumBits) {
Chris Lattnera1888942005-12-12 07:19:13 +0000983 if (NumBits > 64) return 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +0000984 if (NumBits > 32) return Type::Int64Ty;
985 if (NumBits > 16) return Type::Int32Ty;
986 if (NumBits > 8) return Type::Int16Ty;
987 return Type::Int8Ty;
Chris Lattnera1888942005-12-12 07:19:13 +0000988}
989
990/// CanConvertToScalar - V is a pointer. If we can convert the pointee to a
991/// single scalar integer type, return that type. Further, if the use is not
992/// a completely trivial use that mem2reg could promote, set IsNotTrivial. If
993/// there are no uses of this pointer, return Type::VoidTy to differentiate from
994/// failure.
995///
996const Type *SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial) {
997 const Type *UsedType = Type::VoidTy; // No uses, no forced type.
998 const TargetData &TD = getAnalysis<TargetData>();
999 const PointerType *PTy = cast<PointerType>(V->getType());
1000
1001 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1002 Instruction *User = cast<Instruction>(*UI);
1003
1004 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Matthijs Kooijman02518142008-06-05 12:51:53 +00001005 // FIXME: Loads of a first class aggregrate value could be converted to a
1006 // series of loads and insertvalues
1007 if (!LI->getType()->isSingleValueType())
1008 return 0;
1009
Chris Lattner5b121cc2006-10-08 23:28:04 +00001010 if (MergeInType(LI->getType(), UsedType, TD))
Chris Lattnera1888942005-12-12 07:19:13 +00001011 return 0;
1012
1013 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Reid Spencer24d6da52007-01-21 00:29:26 +00001014 // Storing the pointer, not into the value?
Chris Lattnera1888942005-12-12 07:19:13 +00001015 if (SI->getOperand(0) == V) return 0;
Matthijs Kooijman02518142008-06-05 12:51:53 +00001016
1017 // FIXME: Stores of a first class aggregrate value could be converted to a
1018 // series of extractvalues and stores
1019 if (!SI->getOperand(0)->getType()->isSingleValueType())
1020 return 0;
Chris Lattnera1888942005-12-12 07:19:13 +00001021
Chris Lattnerde6df882006-04-14 21:42:41 +00001022 // NOTE: We could handle storing of FP imms into integers here!
Chris Lattnera1888942005-12-12 07:19:13 +00001023
Chris Lattner5b121cc2006-10-08 23:28:04 +00001024 if (MergeInType(SI->getOperand(0)->getType(), UsedType, TD))
Chris Lattnera1888942005-12-12 07:19:13 +00001025 return 0;
Chris Lattnerd22dbdf2006-12-15 07:32:38 +00001026 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Chris Lattnera1888942005-12-12 07:19:13 +00001027 IsNotTrivial = true;
1028 const Type *SubTy = CanConvertToScalar(CI, IsNotTrivial);
Chris Lattner5b121cc2006-10-08 23:28:04 +00001029 if (!SubTy || MergeInType(SubTy, UsedType, TD)) return 0;
Chris Lattnera1888942005-12-12 07:19:13 +00001030 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1031 // Check to see if this is stepping over an element: GEP Ptr, int C
1032 if (GEP->getNumOperands() == 2 && isa<ConstantInt>(GEP->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001033 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
Duncan Sands3cb36502007-11-04 14:43:57 +00001034 unsigned ElSize = TD.getABITypeSize(PTy->getElementType());
Chris Lattnera1888942005-12-12 07:19:13 +00001035 unsigned BitOffset = Idx*ElSize*8;
1036 if (BitOffset > 64 || !isPowerOf2_32(ElSize)) return 0;
1037
1038 IsNotTrivial = true;
1039 const Type *SubElt = CanConvertToScalar(GEP, IsNotTrivial);
1040 if (SubElt == 0) return 0;
Chris Lattner42a75512007-01-15 02:27:26 +00001041 if (SubElt != Type::VoidTy && SubElt->isInteger()) {
Chris Lattnera1888942005-12-12 07:19:13 +00001042 const Type *NewTy =
Duncan Sands3cb36502007-11-04 14:43:57 +00001043 getUIntAtLeastAsBigAs(TD.getABITypeSizeInBits(SubElt)+BitOffset);
Chris Lattner5b121cc2006-10-08 23:28:04 +00001044 if (NewTy == 0 || MergeInType(NewTy, UsedType, TD)) return 0;
Chris Lattnera1888942005-12-12 07:19:13 +00001045 continue;
1046 }
1047 } else if (GEP->getNumOperands() == 3 &&
1048 isa<ConstantInt>(GEP->getOperand(1)) &&
1049 isa<ConstantInt>(GEP->getOperand(2)) &&
Zhou Sheng843f07672007-04-19 05:39:12 +00001050 cast<ConstantInt>(GEP->getOperand(1))->isZero()) {
Chris Lattnera1888942005-12-12 07:19:13 +00001051 // We are stepping into an element, e.g. a structure or an array:
1052 // GEP Ptr, int 0, uint C
1053 const Type *AggTy = PTy->getElementType();
Reid Spencerb83eb642006-10-20 07:07:24 +00001054 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattnera1888942005-12-12 07:19:13 +00001055
1056 if (const ArrayType *ATy = dyn_cast<ArrayType>(AggTy)) {
1057 if (Idx >= ATy->getNumElements()) return 0; // Out of range.
Reid Spencerac9dcb92007-02-15 03:39:18 +00001058 } else if (const VectorType *VectorTy = dyn_cast<VectorType>(AggTy)) {
Dan Gohman07a96762007-07-16 14:29:03 +00001059 // Getting an element of the vector.
Reid Spencerac9dcb92007-02-15 03:39:18 +00001060 if (Idx >= VectorTy->getNumElements()) return 0; // Out of range.
Chris Lattnerde6df882006-04-14 21:42:41 +00001061
Reid Spencerac9dcb92007-02-15 03:39:18 +00001062 // Merge in the vector type.
1063 if (MergeInType(VectorTy, UsedType, TD)) return 0;
Chris Lattnerde6df882006-04-14 21:42:41 +00001064
1065 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
1066 if (SubTy == 0) return 0;
1067
Chris Lattner5b121cc2006-10-08 23:28:04 +00001068 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
Chris Lattnerde6df882006-04-14 21:42:41 +00001069 return 0;
1070
1071 // We'll need to change this to an insert/extract element operation.
1072 IsNotTrivial = true;
1073 continue; // Everything looks ok
1074
Chris Lattnera1888942005-12-12 07:19:13 +00001075 } else if (isa<StructType>(AggTy)) {
1076 // Structs are always ok.
1077 } else {
1078 return 0;
1079 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001080 const Type *NTy = getUIntAtLeastAsBigAs(TD.getABITypeSizeInBits(AggTy));
Chris Lattner5b121cc2006-10-08 23:28:04 +00001081 if (NTy == 0 || MergeInType(NTy, UsedType, TD)) return 0;
Chris Lattnera1888942005-12-12 07:19:13 +00001082 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
1083 if (SubTy == 0) return 0;
Chris Lattner5b121cc2006-10-08 23:28:04 +00001084 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
Chris Lattnera1888942005-12-12 07:19:13 +00001085 return 0;
1086 continue; // Everything looks ok
1087 }
1088 return 0;
1089 } else {
1090 // Cannot handle this!
1091 return 0;
1092 }
1093 }
1094
1095 return UsedType;
1096}
1097
1098/// ConvertToScalar - The specified alloca passes the CanConvertToScalar
1099/// predicate and is non-trivial. Convert it to something that can be trivially
1100/// promoted into a register by mem2reg.
1101void SROA::ConvertToScalar(AllocationInst *AI, const Type *ActualTy) {
Bill Wendlingb7427032006-11-26 09:46:52 +00001102 DOUT << "CONVERT TO SCALAR: " << *AI << " TYPE = "
1103 << *ActualTy << "\n";
Chris Lattnera1888942005-12-12 07:19:13 +00001104 ++NumConverted;
1105
1106 BasicBlock *EntryBlock = AI->getParent();
Dan Gohmanecb7a772007-03-22 16:38:57 +00001107 assert(EntryBlock == &EntryBlock->getParent()->getEntryBlock() &&
Chris Lattnera1888942005-12-12 07:19:13 +00001108 "Not in the entry block!");
1109 EntryBlock->getInstList().remove(AI); // Take the alloca out of the program.
1110
1111 // Create and insert the alloca.
Chris Lattnerde6df882006-04-14 21:42:41 +00001112 AllocaInst *NewAI = new AllocaInst(ActualTy, 0, AI->getName(),
1113 EntryBlock->begin());
Chris Lattnera1888942005-12-12 07:19:13 +00001114 ConvertUsesToScalar(AI, NewAI, 0);
1115 delete AI;
1116}
1117
1118
1119/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
Chris Lattnerde6df882006-04-14 21:42:41 +00001120/// directly. This happens when we are converting an "integer union" to a
1121/// single integer scalar, or when we are converting a "vector union" to a
1122/// vector with insert/extractelement instructions.
1123///
1124/// Offset is an offset from the original alloca, in bits that need to be
1125/// shifted to the right. By the end of this, there should be no uses of Ptr.
Chris Lattnera1888942005-12-12 07:19:13 +00001126void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset) {
1127 while (!Ptr->use_empty()) {
1128 Instruction *User = cast<Instruction>(Ptr->use_back());
1129
1130 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner800de312008-02-29 07:03:13 +00001131 Value *NV = ConvertUsesOfLoadToScalar(LI, NewAI, Offset);
Chris Lattnera1888942005-12-12 07:19:13 +00001132 LI->replaceAllUsesWith(NV);
1133 LI->eraseFromParent();
1134 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1135 assert(SI->getOperand(0) != Ptr && "Consistency error!");
1136
Chris Lattner800de312008-02-29 07:03:13 +00001137 Value *SV = ConvertUsesOfStoreToScalar(SI, NewAI, Offset);
Chris Lattnera1888942005-12-12 07:19:13 +00001138 new StoreInst(SV, NewAI, SI);
1139 SI->eraseFromParent();
1140
Chris Lattnerf4b18182007-04-11 00:57:54 +00001141 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Chris Lattnerb10e0da2008-01-30 00:39:15 +00001142 ConvertUsesToScalar(CI, NewAI, Offset);
Chris Lattnera1888942005-12-12 07:19:13 +00001143 CI->eraseFromParent();
1144 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1145 const PointerType *AggPtrTy =
1146 cast<PointerType>(GEP->getOperand(0)->getType());
1147 const TargetData &TD = getAnalysis<TargetData>();
Duncan Sands3cb36502007-11-04 14:43:57 +00001148 unsigned AggSizeInBits =
1149 TD.getABITypeSizeInBits(AggPtrTy->getElementType());
1150
Chris Lattnera1888942005-12-12 07:19:13 +00001151 // Check to see if this is stepping over an element: GEP Ptr, int C
1152 unsigned NewOffset = Offset;
1153 if (GEP->getNumOperands() == 2) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001154 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
Chris Lattnera1888942005-12-12 07:19:13 +00001155 unsigned BitOffset = Idx*AggSizeInBits;
1156
Chris Lattnerf4b18182007-04-11 00:57:54 +00001157 NewOffset += BitOffset;
Chris Lattnera1888942005-12-12 07:19:13 +00001158 } else if (GEP->getNumOperands() == 3) {
1159 // We know that operand #2 is zero.
Reid Spencerb83eb642006-10-20 07:07:24 +00001160 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattnera1888942005-12-12 07:19:13 +00001161 const Type *AggTy = AggPtrTy->getElementType();
1162 if (const SequentialType *SeqTy = dyn_cast<SequentialType>(AggTy)) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001163 unsigned ElSizeBits =
1164 TD.getABITypeSizeInBits(SeqTy->getElementType());
Chris Lattnera1888942005-12-12 07:19:13 +00001165
Chris Lattnerf4b18182007-04-11 00:57:54 +00001166 NewOffset += ElSizeBits*Idx;
Chris Lattnera1888942005-12-12 07:19:13 +00001167 } else if (const StructType *STy = dyn_cast<StructType>(AggTy)) {
Chris Lattnerb1919e22007-02-10 19:55:17 +00001168 unsigned EltBitOffset =
Duncan Sands3cb36502007-11-04 14:43:57 +00001169 TD.getStructLayout(STy)->getElementOffsetInBits(Idx);
Chris Lattnera1888942005-12-12 07:19:13 +00001170
Chris Lattnerf4b18182007-04-11 00:57:54 +00001171 NewOffset += EltBitOffset;
Chris Lattnera1888942005-12-12 07:19:13 +00001172 } else {
1173 assert(0 && "Unsupported operation!");
1174 abort();
1175 }
1176 } else {
1177 assert(0 && "Unsupported operation!");
1178 abort();
1179 }
1180 ConvertUsesToScalar(GEP, NewAI, NewOffset);
1181 GEP->eraseFromParent();
1182 } else {
1183 assert(0 && "Unsupported operation!");
1184 abort();
1185 }
1186 }
1187}
Chris Lattner79b3bd32007-04-25 06:40:51 +00001188
Chris Lattner800de312008-02-29 07:03:13 +00001189/// ConvertUsesOfLoadToScalar - Convert all of the users the specified load to
1190/// use the new alloca directly, returning the value that should replace the
1191/// load. This happens when we are converting an "integer union" to a
1192/// single integer scalar, or when we are converting a "vector union" to a
1193/// vector with insert/extractelement instructions.
1194///
1195/// Offset is an offset from the original alloca, in bits that need to be
1196/// shifted to the right. By the end of this, there should be no uses of Ptr.
1197Value *SROA::ConvertUsesOfLoadToScalar(LoadInst *LI, AllocaInst *NewAI,
1198 unsigned Offset) {
1199 // The load is a bit extract from NewAI shifted right by Offset bits.
1200 Value *NV = new LoadInst(NewAI, LI->getName(), LI);
1201
1202 if (NV->getType() == LI->getType() && Offset == 0) {
1203 // We win, no conversion needed.
1204 return NV;
1205 }
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001206
1207 // If the result type of the 'union' is a pointer, then this must be ptr->ptr
1208 // cast. Anything else would result in NV being an integer.
1209 if (isa<PointerType>(NV->getType())) {
1210 assert(isa<PointerType>(LI->getType()));
1211 return new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1212 }
Chris Lattner800de312008-02-29 07:03:13 +00001213
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001214 if (const VectorType *VTy = dyn_cast<VectorType>(NV->getType())) {
Chris Lattner800de312008-02-29 07:03:13 +00001215 // If the result alloca is a vector type, this is either an element
1216 // access or a bitcast to another vector type.
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001217 if (isa<VectorType>(LI->getType()))
1218 return new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1219
1220 // Otherwise it must be an element access.
1221 const TargetData &TD = getAnalysis<TargetData>();
1222 unsigned Elt = 0;
1223 if (Offset) {
1224 unsigned EltSize = TD.getABITypeSizeInBits(VTy->getElementType());
1225 Elt = Offset/EltSize;
1226 Offset -= EltSize*Elt;
Chris Lattner800de312008-02-29 07:03:13 +00001227 }
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001228 NV = new ExtractElementInst(NV, ConstantInt::get(Type::Int32Ty, Elt),
1229 "tmp", LI);
1230
1231 // If we're done, return this element.
1232 if (NV->getType() == LI->getType() && Offset == 0)
1233 return NV;
1234 }
1235
1236 const IntegerType *NTy = cast<IntegerType>(NV->getType());
1237
1238 // If this is a big-endian system and the load is narrower than the
1239 // full alloca type, we need to do a shift to get the right bits.
1240 int ShAmt = 0;
1241 const TargetData &TD = getAnalysis<TargetData>();
1242 if (TD.isBigEndian()) {
1243 // On big-endian machines, the lowest bit is stored at the bit offset
1244 // from the pointer given by getTypeStoreSizeInBits. This matters for
1245 // integers with a bitwidth that is not a multiple of 8.
1246 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
1247 TD.getTypeStoreSizeInBits(LI->getType()) - Offset;
1248 } else {
1249 ShAmt = Offset;
1250 }
1251
1252 // Note: we support negative bitwidths (with shl) which are not defined.
1253 // We do this to support (f.e.) loads off the end of a structure where
1254 // only some bits are used.
1255 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001256 NV = BinaryOperator::CreateLShr(NV,
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001257 ConstantInt::get(NV->getType(),ShAmt),
1258 LI->getName(), LI);
1259 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001260 NV = BinaryOperator::CreateShl(NV,
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001261 ConstantInt::get(NV->getType(),-ShAmt),
1262 LI->getName(), LI);
1263
1264 // Finally, unconditionally truncate the integer to the right width.
1265 unsigned LIBitWidth = TD.getTypeSizeInBits(LI->getType());
1266 if (LIBitWidth < NTy->getBitWidth())
1267 NV = new TruncInst(NV, IntegerType::get(LIBitWidth),
1268 LI->getName(), LI);
1269
1270 // If the result is an integer, this is a trunc or bitcast.
1271 if (isa<IntegerType>(LI->getType())) {
1272 // Should be done.
1273 } else if (LI->getType()->isFloatingPoint()) {
1274 // Just do a bitcast, we know the sizes match up.
Chris Lattner800de312008-02-29 07:03:13 +00001275 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1276 } else {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001277 // Otherwise must be a pointer.
1278 NV = new IntToPtrInst(NV, LI->getType(), LI->getName(), LI);
Chris Lattner800de312008-02-29 07:03:13 +00001279 }
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001280 assert(NV->getType() == LI->getType() && "Didn't convert right?");
Chris Lattner800de312008-02-29 07:03:13 +00001281 return NV;
1282}
1283
1284
1285/// ConvertUsesOfStoreToScalar - Convert the specified store to a load+store
1286/// pair of the new alloca directly, returning the value that should be stored
1287/// to the alloca. This happens when we are converting an "integer union" to a
1288/// single integer scalar, or when we are converting a "vector union" to a
1289/// vector with insert/extractelement instructions.
1290///
1291/// Offset is an offset from the original alloca, in bits that need to be
1292/// shifted to the right. By the end of this, there should be no uses of Ptr.
1293Value *SROA::ConvertUsesOfStoreToScalar(StoreInst *SI, AllocaInst *NewAI,
1294 unsigned Offset) {
1295
1296 // Convert the stored type to the actual type, shift it left to insert
1297 // then 'or' into place.
1298 Value *SV = SI->getOperand(0);
1299 const Type *AllocaType = NewAI->getType()->getElementType();
1300 if (SV->getType() == AllocaType && Offset == 0) {
1301 // All is well.
1302 } else if (const VectorType *PTy = dyn_cast<VectorType>(AllocaType)) {
1303 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1304
1305 // If the result alloca is a vector type, this is either an element
1306 // access or a bitcast to another vector type.
1307 if (isa<VectorType>(SV->getType())) {
1308 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1309 } else {
1310 // Must be an element insertion.
1311 const TargetData &TD = getAnalysis<TargetData>();
1312 unsigned Elt = Offset/TD.getABITypeSizeInBits(PTy->getElementType());
Gabor Greif051a9502008-04-06 20:25:17 +00001313 SV = InsertElementInst::Create(Old, SV,
1314 ConstantInt::get(Type::Int32Ty, Elt),
1315 "tmp", SI);
Chris Lattner800de312008-02-29 07:03:13 +00001316 }
1317 } else if (isa<PointerType>(AllocaType)) {
1318 // If the alloca type is a pointer, then all the elements must be
1319 // pointers.
1320 if (SV->getType() != AllocaType)
1321 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1322 } else {
1323 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1324
1325 // If SV is a float, convert it to the appropriate integer type.
1326 // If it is a pointer, do the same, and also handle ptr->ptr casts
1327 // here.
1328 const TargetData &TD = getAnalysis<TargetData>();
1329 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
1330 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
1331 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
1332 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
1333 if (SV->getType()->isFloatingPoint())
1334 SV = new BitCastInst(SV, IntegerType::get(SrcWidth),
1335 SV->getName(), SI);
1336 else if (isa<PointerType>(SV->getType()))
1337 SV = new PtrToIntInst(SV, TD.getIntPtrType(), SV->getName(), SI);
1338
1339 // Always zero extend the value if needed.
1340 if (SV->getType() != AllocaType)
1341 SV = new ZExtInst(SV, AllocaType, SV->getName(), SI);
1342
1343 // If this is a big-endian system and the store is narrower than the
1344 // full alloca type, we need to do a shift to get the right bits.
1345 int ShAmt = 0;
1346 if (TD.isBigEndian()) {
1347 // On big-endian machines, the lowest bit is stored at the bit offset
1348 // from the pointer given by getTypeStoreSizeInBits. This matters for
1349 // integers with a bitwidth that is not a multiple of 8.
1350 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
1351 } else {
1352 ShAmt = Offset;
1353 }
1354
1355 // Note: we support negative bitwidths (with shr) which are not defined.
1356 // We do this to support (f.e.) stores off the end of a structure where
1357 // only some bits in the structure are set.
1358 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1359 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001360 SV = BinaryOperator::CreateShl(SV,
Chris Lattner800de312008-02-29 07:03:13 +00001361 ConstantInt::get(SV->getType(), ShAmt),
1362 SV->getName(), SI);
1363 Mask <<= ShAmt;
1364 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001365 SV = BinaryOperator::CreateLShr(SV,
Chris Lattner800de312008-02-29 07:03:13 +00001366 ConstantInt::get(SV->getType(),-ShAmt),
1367 SV->getName(), SI);
1368 Mask = Mask.lshr(ShAmt);
1369 }
1370
1371 // Mask out the bits we are about to insert from the old value, and or
1372 // in the new bits.
1373 if (SrcWidth != DestWidth) {
1374 assert(DestWidth > SrcWidth);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001375 Old = BinaryOperator::CreateAnd(Old, ConstantInt::get(~Mask),
Chris Lattner800de312008-02-29 07:03:13 +00001376 Old->getName()+".mask", SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001377 SV = BinaryOperator::CreateOr(Old, SV, SV->getName()+".ins", SI);
Chris Lattner800de312008-02-29 07:03:13 +00001378 }
1379 }
1380 return SV;
1381}
1382
1383
Chris Lattner79b3bd32007-04-25 06:40:51 +00001384
1385/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1386/// some part of a constant global variable. This intentionally only accepts
1387/// constant expressions because we don't can't rewrite arbitrary instructions.
1388static bool PointsToConstantGlobal(Value *V) {
1389 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1390 return GV->isConstant();
1391 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1392 if (CE->getOpcode() == Instruction::BitCast ||
1393 CE->getOpcode() == Instruction::GetElementPtr)
1394 return PointsToConstantGlobal(CE->getOperand(0));
1395 return false;
1396}
1397
1398/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1399/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1400/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1401/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1402/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1403/// the alloca, and if the source pointer is a pointer to a constant global, we
1404/// can optimize this.
1405static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1406 bool isOffset) {
1407 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1408 if (isa<LoadInst>(*UI)) {
1409 // Ignore loads, they are always ok.
1410 continue;
1411 }
1412 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1413 // If uses of the bitcast are ok, we are ok.
1414 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1415 return false;
1416 continue;
1417 }
1418 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1419 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1420 // doesn't, it does.
1421 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1422 isOffset || !GEP->hasAllZeroIndices()))
1423 return false;
1424 continue;
1425 }
1426
1427 // If this is isn't our memcpy/memmove, reject it as something we can't
1428 // handle.
1429 if (!isa<MemCpyInst>(*UI) && !isa<MemMoveInst>(*UI))
1430 return false;
1431
1432 // If we already have seen a copy, reject the second one.
1433 if (TheCopy) return false;
1434
1435 // If the pointer has been offset from the start of the alloca, we can't
1436 // safely handle this.
1437 if (isOffset) return false;
1438
1439 // If the memintrinsic isn't using the alloca as the dest, reject it.
1440 if (UI.getOperandNo() != 1) return false;
1441
1442 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1443
1444 // If the source of the memcpy/move is not a constant global, reject it.
1445 if (!PointsToConstantGlobal(MI->getOperand(2)))
1446 return false;
1447
1448 // Otherwise, the transform is safe. Remember the copy instruction.
1449 TheCopy = MI;
1450 }
1451 return true;
1452}
1453
1454/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1455/// modified by a copy from a constant global. If we can prove this, we can
1456/// replace any uses of the alloca with uses of the global directly.
1457Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocationInst *AI) {
1458 Instruction *TheCopy = 0;
1459 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1460 return TheCopy;
1461 return 0;
1462}