blob: ae0eebcbd214014904be4867bf892dff3673e4d3 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
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
13// 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.
19//
20//===----------------------------------------------------------------------===//
21
22#define DEBUG_TYPE "scalarrepl"
23#include "llvm/Transforms/Scalar.h"
24#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
26#include "llvm/Function.h"
27#include "llvm/GlobalVariable.h"
28#include "llvm/Instructions.h"
29#include "llvm/IntrinsicInst.h"
30#include "llvm/Pass.h"
31#include "llvm/Analysis/Dominators.h"
32#include "llvm/Target/TargetData.h"
33#include "llvm/Transforms/Utils/PromoteMemToReg.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/Support/GetElementPtrTypeIterator.h"
36#include "llvm/Support/MathExtras.h"
37#include "llvm/Support/Compiler.h"
38#include "llvm/ADT/SmallVector.h"
39#include "llvm/ADT/Statistic.h"
40#include "llvm/ADT/StringExtras.h"
41using namespace llvm;
42
43STATISTIC(NumReplaced, "Number of allocas broken up");
44STATISTIC(NumPromoted, "Number of allocas promoted");
45STATISTIC(NumConverted, "Number of aggregates converted to scalar");
46STATISTIC(NumGlobals, "Number of allocas copied from constant global");
47
48namespace {
49 struct VISIBILITY_HIDDEN SROA : public FunctionPass {
50 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +000051 explicit SROA(signed T = -1) : FunctionPass(&ID) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000052 if (T == -1)
Chris Lattner6d7faec2007-08-02 21:33:36 +000053 SRThreshold = 128;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000054 else
55 SRThreshold = T;
56 }
57
58 bool runOnFunction(Function &F);
59
60 bool performScalarRepl(Function &F);
61 bool performPromotion(Function &F);
62
63 // 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 {
66 AU.addRequired<DominatorTree>();
67 AU.addRequired<DominanceFrontier>();
68 AU.addRequired<TargetData>();
69 AU.setPreservesCFG();
70 }
71
72 private:
Chris Lattner3fd59362009-01-07 06:34:28 +000073 TargetData *TD;
74
Dan Gohmanf17a25c2007-07-18 16:29:46 +000075 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
76 /// information about the uses. All these fields are initialized to false
77 /// and set to true when something is learned.
78 struct AllocaInfo {
79 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
80 bool isUnsafe : 1;
81
82 /// needsCanon - This is set to true if there is some use of the alloca
83 /// that requires canonicalization.
84 bool needsCanon : 1;
85
86 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
87 bool isMemCpySrc : 1;
88
89 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
90 bool isMemCpyDst : 1;
91
92 AllocaInfo()
93 : isUnsafe(false), needsCanon(false),
94 isMemCpySrc(false), isMemCpyDst(false) {}
95 };
96
97 unsigned SRThreshold;
98
99 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
100
101 int isSafeAllocaToScalarRepl(AllocationInst *AI);
102
103 void isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
104 AllocaInfo &Info);
105 void isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
106 AllocaInfo &Info);
107 void isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
108 unsigned OpNo, AllocaInfo &Info);
109 void isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI,
110 AllocaInfo &Info);
111
112 void DoScalarReplacement(AllocationInst *AI,
113 std::vector<AllocationInst*> &WorkList);
114 void CanonicalizeAllocaUsers(AllocationInst *AI);
115 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
116
117 void RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
118 SmallVector<AllocaInst*, 32> &NewElts);
119
120 const Type *CanConvertToScalar(Value *V, bool &IsNotTrivial);
121 void ConvertToScalar(AllocationInst *AI, const Type *Ty);
122 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset);
Chris Lattner41d58652008-02-29 07:03:13 +0000123 Value *ConvertUsesOfLoadToScalar(LoadInst *LI, AllocaInst *NewAI,
124 unsigned Offset);
125 Value *ConvertUsesOfStoreToScalar(StoreInst *SI, AllocaInst *NewAI,
126 unsigned Offset);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000127 static Instruction *isOnlyCopiedFromConstantGlobal(AllocationInst *AI);
128 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000129}
130
Dan Gohman089efff2008-05-13 00:00:25 +0000131char SROA::ID = 0;
132static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
133
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000134// Public interface to the ScalarReplAggregates pass
135FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
136 return new SROA(Threshold);
137}
138
139
140bool SROA::runOnFunction(Function &F) {
Chris Lattner3fd59362009-01-07 06:34:28 +0000141 TD = &getAnalysis<TargetData>();
142
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000143 bool Changed = performPromotion(F);
144 while (1) {
145 bool LocalChange = performScalarRepl(F);
146 if (!LocalChange) break; // No need to repromote if no scalarrepl
147 Changed = true;
148 LocalChange = performPromotion(F);
149 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
150 }
151
152 return Changed;
153}
154
155
156bool SROA::performPromotion(Function &F) {
157 std::vector<AllocaInst*> Allocas;
158 DominatorTree &DT = getAnalysis<DominatorTree>();
159 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
160
161 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
162
163 bool Changed = false;
164
165 while (1) {
166 Allocas.clear();
167
168 // Find allocas that are safe to promote, by looking at all instructions in
169 // the entry node
170 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
171 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
172 if (isAllocaPromotable(AI))
173 Allocas.push_back(AI);
174
175 if (Allocas.empty()) break;
176
177 PromoteMemToReg(Allocas, DT, DF);
178 NumPromoted += Allocas.size();
179 Changed = true;
180 }
181
182 return Changed;
183}
184
Chris Lattner0e99e692008-06-22 17:46:21 +0000185/// getNumSAElements - Return the number of elements in the specific struct or
186/// array.
187static uint64_t getNumSAElements(const Type *T) {
188 if (const StructType *ST = dyn_cast<StructType>(T))
189 return ST->getNumElements();
190 return cast<ArrayType>(T)->getNumElements();
191}
192
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000193// performScalarRepl - This algorithm is a simple worklist driven algorithm,
194// which runs on all of the malloc/alloca instructions in the function, removing
195// them if they are only used by getelementptr instructions.
196//
197bool SROA::performScalarRepl(Function &F) {
198 std::vector<AllocationInst*> WorkList;
199
200 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
201 BasicBlock &BB = F.getEntryBlock();
202 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
203 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
204 WorkList.push_back(A);
205
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000206 // Process the worklist
207 bool Changed = false;
208 while (!WorkList.empty()) {
209 AllocationInst *AI = WorkList.back();
210 WorkList.pop_back();
211
212 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
213 // with unused elements.
214 if (AI->use_empty()) {
215 AI->eraseFromParent();
216 continue;
217 }
218
219 // If we can turn this aggregate value (potentially with casts) into a
220 // simple scalar value that can be mem2reg'd into a register value.
221 bool IsNotTrivial = false;
222 if (const Type *ActualType = CanConvertToScalar(AI, IsNotTrivial))
223 if (IsNotTrivial && ActualType != Type::VoidTy) {
224 ConvertToScalar(AI, ActualType);
225 Changed = true;
226 continue;
227 }
228
229 // Check to see if we can perform the core SROA transformation. We cannot
230 // transform the allocation instruction if it is an array allocation
231 // (allocations OF arrays are ok though), and an allocation of a scalar
232 // value cannot be decomposed at all.
233 if (!AI->isArrayAllocation() &&
234 (isa<StructType>(AI->getAllocatedType()) ||
235 isa<ArrayType>(AI->getAllocatedType())) &&
236 AI->getAllocatedType()->isSized() &&
Chris Lattner0e99e692008-06-22 17:46:21 +0000237 // Do not promote any struct whose size is larger than "128" bytes.
Chris Lattner3fd59362009-01-07 06:34:28 +0000238 TD->getABITypeSize(AI->getAllocatedType()) < SRThreshold &&
Chris Lattner0e99e692008-06-22 17:46:21 +0000239 // Do not promote any struct into more than "32" separate vars.
240 getNumSAElements(AI->getAllocatedType()) < SRThreshold/4) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000241 // Check that all of the users of the allocation are capable of being
242 // transformed.
243 switch (isSafeAllocaToScalarRepl(AI)) {
244 default: assert(0 && "Unexpected value!");
245 case 0: // Not safe to scalar replace.
246 break;
247 case 1: // Safe, but requires cleanup/canonicalizations first
248 CanonicalizeAllocaUsers(AI);
249 // FALL THROUGH.
250 case 3: // Safe to scalar replace.
251 DoScalarReplacement(AI, WorkList);
252 Changed = true;
253 continue;
254 }
255 }
256
257 // Check to see if this allocation is only modified by a memcpy/memmove from
258 // a constant global. If this is the case, we can change all users to use
259 // the constant global instead. This is commonly produced by the CFE by
260 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
261 // is only subsequently read.
262 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
263 DOUT << "Found alloca equal to global: " << *AI;
264 DOUT << " memcpy = " << *TheCopy;
265 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
266 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
267 TheCopy->eraseFromParent(); // Don't mutate the global.
268 AI->eraseFromParent();
269 ++NumGlobals;
270 Changed = true;
271 continue;
272 }
273
274 // Otherwise, couldn't process this.
275 }
276
277 return Changed;
278}
279
280/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
281/// predicate, do SROA now.
282void SROA::DoScalarReplacement(AllocationInst *AI,
283 std::vector<AllocationInst*> &WorkList) {
284 DOUT << "Found inst to SROA: " << *AI;
285 SmallVector<AllocaInst*, 32> ElementAllocas;
286 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
287 ElementAllocas.reserve(ST->getNumContainedTypes());
288 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
289 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
290 AI->getAlignment(),
291 AI->getName() + "." + utostr(i), AI);
292 ElementAllocas.push_back(NA);
293 WorkList.push_back(NA); // Add to worklist for recursive processing
294 }
295 } else {
296 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
297 ElementAllocas.reserve(AT->getNumElements());
298 const Type *ElTy = AT->getElementType();
299 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
300 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
301 AI->getName() + "." + utostr(i), AI);
302 ElementAllocas.push_back(NA);
303 WorkList.push_back(NA); // Add to worklist for recursive processing
304 }
305 }
306
307 // Now that we have created the alloca instructions that we want to use,
308 // expand the getelementptr instructions to use them.
309 //
310 while (!AI->use_empty()) {
311 Instruction *User = cast<Instruction>(AI->use_back());
312 if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
313 RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
314 BCInst->eraseFromParent();
315 continue;
316 }
317
Chris Lattner19e61a42008-06-23 17:11:23 +0000318 // Replace:
319 // %res = load { i32, i32 }* %alloc
320 // with:
321 // %load.0 = load i32* %alloc.0
322 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
323 // %load.1 = load i32* %alloc.1
324 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
Matthijs Kooijman001006a2008-06-05 12:51:53 +0000325 // (Also works for arrays instead of structs)
326 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
327 Value *Insert = UndefValue::get(LI->getType());
328 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
329 Value *Load = new LoadInst(ElementAllocas[i], "load", LI);
330 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
331 }
332 LI->replaceAllUsesWith(Insert);
333 LI->eraseFromParent();
334 continue;
335 }
336
Chris Lattner19e61a42008-06-23 17:11:23 +0000337 // Replace:
338 // store { i32, i32 } %val, { i32, i32 }* %alloc
339 // with:
340 // %val.0 = extractvalue { i32, i32 } %val, 0
341 // store i32 %val.0, i32* %alloc.0
342 // %val.1 = extractvalue { i32, i32 } %val, 1
343 // store i32 %val.1, i32* %alloc.1
Matthijs Kooijman001006a2008-06-05 12:51:53 +0000344 // (Also works for arrays instead of structs)
345 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
346 Value *Val = SI->getOperand(0);
347 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
348 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
349 new StoreInst(Extract, ElementAllocas[i], SI);
350 }
351 SI->eraseFromParent();
352 continue;
353 }
354
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000355 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
356 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
357 unsigned Idx =
358 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
359
360 assert(Idx < ElementAllocas.size() && "Index out of range?");
361 AllocaInst *AllocaToUse = ElementAllocas[Idx];
362
363 Value *RepValue;
364 if (GEPI->getNumOperands() == 3) {
365 // Do not insert a new getelementptr instruction with zero indices, only
366 // to have it optimized out later.
367 RepValue = AllocaToUse;
368 } else {
369 // We are indexing deeply into the structure, so we still need a
370 // getelement ptr instruction to finish the indexing. This may be
371 // expanded itself once the worklist is rerun.
372 //
373 SmallVector<Value*, 8> NewArgs;
374 NewArgs.push_back(Constant::getNullValue(Type::Int32Ty));
375 NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
Gabor Greifd6da1d02008-04-06 20:25:17 +0000376 RepValue = GetElementPtrInst::Create(AllocaToUse, NewArgs.begin(),
377 NewArgs.end(), "", GEPI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000378 RepValue->takeName(GEPI);
379 }
380
381 // If this GEP is to the start of the aggregate, check for memcpys.
Chris Lattner85591c62009-01-07 06:25:07 +0000382 if (Idx == 0 && GEPI->hasAllZeroIndices())
383 RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000384
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
396
397/// isSafeElementUse - Check to see if this use is an allowed use for a
398/// getelementptr instruction of an array aggregate allocation. isFirstElt
399/// indicates whether Ptr is known to the start of the aggregate.
400///
401void SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
402 AllocaInfo &Info) {
403 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
410 if (User->getOperand(0) == Ptr) return MarkUnsafe(Info);
411 break;
412 case Instruction::GetElementPtr: {
413 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
414 bool AreAllZeroIndices = isFirstElt;
415 if (GEP->getNumOperands() > 1) {
416 if (!isa<ConstantInt>(GEP->getOperand(1)) ||
417 !cast<ConstantInt>(GEP->getOperand(1))->isZero())
418 // Using pointer arithmetic to navigate the array.
419 return MarkUnsafe(Info);
420
Chris Lattner85591c62009-01-07 06:25:07 +0000421 if (AreAllZeroIndices)
422 AreAllZeroIndices = GEP->hasAllZeroIndices();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000423 }
424 isSafeElementUse(GEP, AreAllZeroIndices, AI, Info);
425 if (Info.isUnsafe) return;
426 break;
427 }
428 case Instruction::BitCast:
429 if (isFirstElt) {
430 isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI, Info);
431 if (Info.isUnsafe) return;
432 break;
433 }
434 DOUT << " Transformation preventing inst: " << *User;
435 return MarkUnsafe(Info);
436 case Instruction::Call:
437 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
438 if (isFirstElt) {
439 isSafeMemIntrinsicOnAllocation(MI, AI, I.getOperandNo(), Info);
440 if (Info.isUnsafe) return;
441 break;
442 }
443 }
444 DOUT << " Transformation preventing inst: " << *User;
445 return MarkUnsafe(Info);
446 default:
447 DOUT << " Transformation preventing inst: " << *User;
448 return MarkUnsafe(Info);
449 }
450 }
451 return; // All users look ok :)
452}
453
454/// AllUsersAreLoads - Return true if all users of this value are loads.
455static bool AllUsersAreLoads(Value *Ptr) {
456 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
457 I != E; ++I)
458 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
459 return false;
460 return true;
461}
462
463/// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
464/// aggregate allocation.
465///
466void SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
467 AllocaInfo &Info) {
468 if (BitCastInst *C = dyn_cast<BitCastInst>(User))
469 return isSafeUseOfBitCastedAllocation(C, AI, Info);
470
Matthijs Kooijman001006a2008-06-05 12:51:53 +0000471 if (isa<LoadInst>(User))
472 return; // Loads (returning a first class aggregrate) are always rewritable
473
474 if (isa<StoreInst>(User) && User->getOperand(0) != AI)
475 return; // Store is ok if storing INTO the pointer, not storing the pointer
476
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000477 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User);
478 if (GEPI == 0)
479 return MarkUnsafe(Info);
480
481 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
482
483 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
484 if (I == E ||
485 I.getOperand() != Constant::getNullValue(I.getOperand()->getType())) {
486 return MarkUnsafe(Info);
487 }
488
489 ++I;
490 if (I == E) return MarkUnsafe(Info); // ran out of GEP indices??
491
492 bool IsAllZeroIndices = true;
493
Chris Lattnerd324da02008-08-23 05:21:06 +0000494 // If the first index is a non-constant index into an array, see if we can
495 // handle it as a special case.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000496 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
Chris Lattnerd324da02008-08-23 05:21:06 +0000497 if (!isa<ConstantInt>(I.getOperand())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000498 IsAllZeroIndices = 0;
Chris Lattnerd324da02008-08-23 05:21:06 +0000499 uint64_t NumElements = AT->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000500
501 // If this is an array index and the index is not constant, we cannot
502 // promote... that is unless the array has exactly one or two elements in
503 // it, in which case we CAN promote it, but we have to canonicalize this
504 // out if this is the only problem.
505 if ((NumElements == 1 || NumElements == 2) &&
506 AllUsersAreLoads(GEPI)) {
507 Info.needsCanon = true;
508 return; // Canonicalization required!
509 }
510 return MarkUnsafe(Info);
511 }
512 }
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000513
Chris Lattnerd324da02008-08-23 05:21:06 +0000514 // Walk through the GEP type indices, checking the types that this indexes
515 // into.
516 for (; I != E; ++I) {
517 // Ignore struct elements, no extra checking needed for these.
518 if (isa<StructType>(*I))
519 continue;
520
Chris Lattnerd324da02008-08-23 05:21:06 +0000521 ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
522 if (!IdxVal) return MarkUnsafe(Info);
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000523
524 // Are all indices still zero?
Chris Lattnerd324da02008-08-23 05:21:06 +0000525 IsAllZeroIndices &= IdxVal->isZero();
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000526
527 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
528 // This GEP indexes an array. Verify that this is an in-range constant
529 // integer. Specifically, consider A[0][i]. We cannot know that the user
530 // isn't doing invalid things like allowing i to index an out-of-range
531 // subscript that accesses A[1]. Because of this, we have to reject SROA
Dale Johannesen1f9b1862008-11-04 20:54:03 +0000532 // of any accesses into structs where any of the components are variables.
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000533 if (IdxVal->getZExtValue() >= AT->getNumElements())
534 return MarkUnsafe(Info);
Dale Johannesen1f9b1862008-11-04 20:54:03 +0000535 } else if (const VectorType *VT = dyn_cast<VectorType>(*I)) {
536 if (IdxVal->getZExtValue() >= VT->getNumElements())
537 return MarkUnsafe(Info);
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000538 }
Chris Lattnerd324da02008-08-23 05:21:06 +0000539 }
540
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000541 // If there are any non-simple uses of this getelementptr, make sure to reject
542 // them.
543 return isSafeElementUse(GEPI, IsAllZeroIndices, AI, Info);
544}
545
546/// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
547/// intrinsic can be promoted by SROA. At this point, we know that the operand
548/// of the memintrinsic is a pointer to the beginning of the allocation.
549void SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
550 unsigned OpNo, AllocaInfo &Info) {
551 // If not constant length, give up.
552 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
553 if (!Length) return MarkUnsafe(Info);
554
555 // If not the whole aggregate, give up.
Duncan Sandsae5fd622007-11-04 14:43:57 +0000556 if (Length->getZExtValue() !=
Chris Lattner3fd59362009-01-07 06:34:28 +0000557 TD->getABITypeSize(AI->getType()->getElementType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000558 return MarkUnsafe(Info);
559
560 // We only know about memcpy/memset/memmove.
561 if (!isa<MemCpyInst>(MI) && !isa<MemSetInst>(MI) && !isa<MemMoveInst>(MI))
562 return MarkUnsafe(Info);
563
564 // Otherwise, we can transform it. Determine whether this is a memcpy/set
565 // into or out of the aggregate.
566 if (OpNo == 1)
567 Info.isMemCpyDst = true;
568 else {
569 assert(OpNo == 2);
570 Info.isMemCpySrc = true;
571 }
572}
573
574/// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
575/// are
576void SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI,
577 AllocaInfo &Info) {
578 for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
579 UI != E; ++UI) {
580 if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
581 isSafeUseOfBitCastedAllocation(BCU, AI, Info);
582 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
583 isSafeMemIntrinsicOnAllocation(MI, AI, UI.getOperandNo(), Info);
584 } else {
585 return MarkUnsafe(Info);
586 }
587 if (Info.isUnsafe) return;
588 }
589}
590
591/// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
592/// to its first element. Transform users of the cast to use the new values
593/// instead.
594void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
595 SmallVector<AllocaInst*, 32> &NewElts) {
596 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000597
598 Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
599 while (UI != UE) {
600 if (BitCastInst *BCU = dyn_cast<BitCastInst>(*UI)) {
601 RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
602 ++UI;
603 BCU->eraseFromParent();
604 continue;
605 }
606
607 // Otherwise, must be memcpy/memmove/memset of the entire aggregate. Split
608 // into one per element.
609 MemIntrinsic *MI = dyn_cast<MemIntrinsic>(*UI);
610
611 // If it's not a mem intrinsic, it must be some other user of a gep of the
612 // first pointer. Just leave these alone.
613 if (!MI) {
614 ++UI;
615 continue;
616 }
617
618 // If this is a memcpy/memmove, construct the other pointer as the
619 // appropriate type.
620 Value *OtherPtr = 0;
621 if (MemCpyInst *MCI = dyn_cast<MemCpyInst>(MI)) {
622 if (BCInst == MCI->getRawDest())
623 OtherPtr = MCI->getRawSource();
624 else {
625 assert(BCInst == MCI->getRawSource());
626 OtherPtr = MCI->getRawDest();
627 }
628 } else if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
629 if (BCInst == MMI->getRawDest())
630 OtherPtr = MMI->getRawSource();
631 else {
632 assert(BCInst == MMI->getRawSource());
633 OtherPtr = MMI->getRawDest();
634 }
635 }
636
637 // If there is an other pointer, we want to convert it to the same pointer
638 // type as AI has, so we can GEP through it.
639 if (OtherPtr) {
640 // It is likely that OtherPtr is a bitcast, if so, remove it.
641 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
642 OtherPtr = BC->getOperand(0);
Chris Lattner85591c62009-01-07 06:25:07 +0000643 // All zero GEPs are effectively bitcasts.
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000644 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr))
645 if (GEP->hasAllZeroIndices())
646 OtherPtr = GEP->getOperand(0);
647
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000648 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
649 if (BCE->getOpcode() == Instruction::BitCast)
650 OtherPtr = BCE->getOperand(0);
651
652 // If the pointer is not the right type, insert a bitcast to the right
653 // type.
654 if (OtherPtr->getType() != AI->getType())
655 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
656 MI);
657 }
658
659 // Process each element of the aggregate.
660 Value *TheFn = MI->getOperand(0);
661 const Type *BytePtrTy = MI->getRawDest()->getType();
662 bool SROADest = MI->getRawDest() == BCInst;
663
664 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
665 // If this is a memcpy/memmove, emit a GEP of the other element address.
666 Value *OtherElt = 0;
667 if (OtherPtr) {
Chris Lattner0e99e692008-06-22 17:46:21 +0000668 Value *Idx[2] = { Zero, ConstantInt::get(Type::Int32Ty, i) };
Gabor Greifd6da1d02008-04-06 20:25:17 +0000669 OtherElt = GetElementPtrInst::Create(OtherPtr, Idx, Idx + 2,
Chris Lattner0e99e692008-06-22 17:46:21 +0000670 OtherPtr->getNameStr()+"."+utostr(i),
Gabor Greifd6da1d02008-04-06 20:25:17 +0000671 MI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000672 }
673
674 Value *EltPtr = NewElts[i];
675 const Type *EltTy =cast<PointerType>(EltPtr->getType())->getElementType();
676
677 // If we got down to a scalar, insert a load or store as appropriate.
Dan Gohman66aff3a2008-05-23 00:12:03 +0000678 if (EltTy->isSingleValueType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000679 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
680 Value *Elt = new LoadInst(SROADest ? OtherElt : EltPtr, "tmp",
681 MI);
682 new StoreInst(Elt, SROADest ? EltPtr : OtherElt, MI);
683 continue;
684 } else {
685 assert(isa<MemSetInst>(MI));
686
687 // If the stored element is zero (common case), just store a null
688 // constant.
689 Constant *StoreVal;
690 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
691 if (CI->isZero()) {
692 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
693 } else {
694 // If EltTy is a vector type, get the element type.
695 const Type *ValTy = EltTy;
696 if (const VectorType *VTy = dyn_cast<VectorType>(ValTy))
697 ValTy = VTy->getElementType();
Duncan Sandsae5fd622007-11-04 14:43:57 +0000698
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000699 // Construct an integer with the right value.
Chris Lattner3fd59362009-01-07 06:34:28 +0000700 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
Duncan Sandsae5fd622007-11-04 14:43:57 +0000701 APInt OneVal(EltSize, CI->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000702 APInt TotalVal(OneVal);
703 // Set each byte.
Duncan Sandsae5fd622007-11-04 14:43:57 +0000704 for (unsigned i = 0; 8*i < EltSize; ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000705 TotalVal = TotalVal.shl(8);
706 TotalVal |= OneVal;
707 }
Duncan Sandsae5fd622007-11-04 14:43:57 +0000708
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000709 // Convert the integer value to the appropriate type.
710 StoreVal = ConstantInt::get(TotalVal);
711 if (isa<PointerType>(ValTy))
712 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
713 else if (ValTy->isFloatingPoint())
714 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
715 assert(StoreVal->getType() == ValTy && "Type mismatch!");
716
717 // If the requested value was a vector constant, create it.
718 if (EltTy != ValTy) {
719 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
720 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
721 StoreVal = ConstantVector::get(&Elts[0], NumElts);
722 }
723 }
724 new StoreInst(StoreVal, EltPtr, MI);
725 continue;
726 }
727 // Otherwise, if we're storing a byte variable, use a memset call for
728 // this element.
729 }
730 }
731
732 // Cast the element pointer to BytePtrTy.
733 if (EltPtr->getType() != BytePtrTy)
734 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
735
736 // Cast the other pointer (if we have one) to BytePtrTy.
737 if (OtherElt && OtherElt->getType() != BytePtrTy)
738 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
739 MI);
740
Chris Lattner3fd59362009-01-07 06:34:28 +0000741 unsigned EltSize = TD->getABITypeSize(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000742
743 // Finally, insert the meminst for this element.
744 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
745 Value *Ops[] = {
746 SROADest ? EltPtr : OtherElt, // Dest ptr
747 SROADest ? OtherElt : EltPtr, // Src ptr
748 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
749 Zero // Align
750 };
Gabor Greifd6da1d02008-04-06 20:25:17 +0000751 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000752 } else {
753 assert(isa<MemSetInst>(MI));
754 Value *Ops[] = {
755 EltPtr, MI->getOperand(2), // Dest, Value,
756 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
757 Zero // Align
758 };
Gabor Greifd6da1d02008-04-06 20:25:17 +0000759 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000760 }
761 }
762
763 // Finally, MI is now dead, as we've modified its actions to occur on all of
764 // the elements of the aggregate.
765 ++UI;
766 MI->eraseFromParent();
767 }
768}
769
Duncan Sandsae5fd622007-11-04 14:43:57 +0000770/// HasPadding - Return true if the specified type has any structure or
771/// alignment padding, false otherwise.
Duncan Sands4afc5752008-06-04 08:21:45 +0000772static bool HasPadding(const Type *Ty, const TargetData &TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000773 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
774 const StructLayout *SL = TD.getStructLayout(STy);
775 unsigned PrevFieldBitOffset = 0;
776 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan Sandsae5fd622007-11-04 14:43:57 +0000777 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
778
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000779 // Padding in sub-elements?
Duncan Sands4afc5752008-06-04 08:21:45 +0000780 if (HasPadding(STy->getElementType(i), TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000781 return true;
Duncan Sandsae5fd622007-11-04 14:43:57 +0000782
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000783 // Check to see if there is any padding between this element and the
784 // previous one.
785 if (i) {
Duncan Sandsae5fd622007-11-04 14:43:57 +0000786 unsigned PrevFieldEnd =
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000787 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
788 if (PrevFieldEnd < FieldBitOffset)
789 return true;
790 }
Duncan Sandsae5fd622007-11-04 14:43:57 +0000791
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000792 PrevFieldBitOffset = FieldBitOffset;
793 }
Duncan Sandsae5fd622007-11-04 14:43:57 +0000794
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000795 // Check for tail padding.
796 if (unsigned EltCount = STy->getNumElements()) {
797 unsigned PrevFieldEnd = PrevFieldBitOffset +
798 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
Duncan Sandsae5fd622007-11-04 14:43:57 +0000799 if (PrevFieldEnd < SL->getSizeInBits())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000800 return true;
801 }
802
803 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Duncan Sands4afc5752008-06-04 08:21:45 +0000804 return HasPadding(ATy->getElementType(), TD);
Duncan Sandsae5fd622007-11-04 14:43:57 +0000805 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
Duncan Sands4afc5752008-06-04 08:21:45 +0000806 return HasPadding(VTy->getElementType(), TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000807 }
Duncan Sands4afc5752008-06-04 08:21:45 +0000808 return TD.getTypeSizeInBits(Ty) != TD.getABITypeSizeInBits(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000809}
810
811/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
812/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
813/// or 1 if safe after canonicalization has been performed.
814///
815int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
816 // Loop over the use list of the alloca. We can only transform it if all of
817 // the users are safe to transform.
818 AllocaInfo Info;
819
820 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
821 I != E; ++I) {
822 isSafeUseOfAllocation(cast<Instruction>(*I), AI, Info);
823 if (Info.isUnsafe) {
824 DOUT << "Cannot transform: " << *AI << " due to user: " << **I;
825 return 0;
826 }
827 }
828
829 // Okay, we know all the users are promotable. If the aggregate is a memcpy
830 // source and destination, we have to be careful. In particular, the memcpy
831 // could be moving around elements that live in structure padding of the LLVM
832 // types, but may actually be used. In these cases, we refuse to promote the
833 // struct.
834 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Chris Lattner3fd59362009-01-07 06:34:28 +0000835 HasPadding(AI->getType()->getElementType(), *TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000836 return 0;
Duncan Sandsae5fd622007-11-04 14:43:57 +0000837
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000838 // If we require cleanup, return 1, otherwise return 3.
839 return Info.needsCanon ? 1 : 3;
840}
841
842/// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified
843/// allocation, but only if cleaned up, perform the cleanups required.
844void SROA::CanonicalizeAllocaUsers(AllocationInst *AI) {
845 // At this point, we know that the end result will be SROA'd and promoted, so
846 // we can insert ugly code if required so long as sroa+mem2reg will clean it
847 // up.
848 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
849 UI != E; ) {
850 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI++);
851 if (!GEPI) continue;
852 gep_type_iterator I = gep_type_begin(GEPI);
853 ++I;
854
855 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
856 uint64_t NumElements = AT->getNumElements();
857
858 if (!isa<ConstantInt>(I.getOperand())) {
859 if (NumElements == 1) {
860 GEPI->setOperand(2, Constant::getNullValue(Type::Int32Ty));
861 } else {
862 assert(NumElements == 2 && "Unhandled case!");
863 // All users of the GEP must be loads. At each use of the GEP, insert
864 // two loads of the appropriate indexed GEP and select between them.
865 Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(),
866 Constant::getNullValue(I.getOperand()->getType()),
867 "isone", GEPI);
868 // Insert the new GEP instructions, which are properly indexed.
869 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
870 Indices[1] = Constant::getNullValue(Type::Int32Ty);
Gabor Greifd6da1d02008-04-06 20:25:17 +0000871 Value *ZeroIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
872 Indices.begin(),
873 Indices.end(),
874 GEPI->getName()+".0", GEPI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000875 Indices[1] = ConstantInt::get(Type::Int32Ty, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +0000876 Value *OneIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
877 Indices.begin(),
878 Indices.end(),
879 GEPI->getName()+".1", GEPI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000880 // Replace all loads of the variable index GEP with loads from both
881 // indexes and a select.
882 while (!GEPI->use_empty()) {
883 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
884 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
885 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
Gabor Greifd6da1d02008-04-06 20:25:17 +0000886 Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000887 LI->replaceAllUsesWith(R);
888 LI->eraseFromParent();
889 }
890 GEPI->eraseFromParent();
891 }
892 }
893 }
894 }
895}
896
897/// MergeInType - Add the 'In' type to the accumulated type so far. If the
898/// types are incompatible, return true, otherwise update Accum and return
899/// false.
900///
901/// There are three cases we handle here:
902/// 1) An effectively-integer union, where the pieces are stored into as
903/// smaller integers (common with byte swap and other idioms).
904/// 2) A union of vector types of the same size and potentially its elements.
905/// Here we turn element accesses into insert/extract element operations.
906/// 3) A union of scalar types, such as int/float or int/pointer. Here we
907/// merge together into integers, allowing the xform to work with #1 as
908/// well.
909static bool MergeInType(const Type *In, const Type *&Accum,
910 const TargetData &TD) {
911 // If this is our first type, just use it.
912 const VectorType *PTy;
913 if (Accum == Type::VoidTy || In == Accum) {
914 Accum = In;
915 } else if (In == Type::VoidTy) {
916 // Noop.
917 } else if (In->isInteger() && Accum->isInteger()) { // integer union.
918 // Otherwise pick whichever type is larger.
919 if (cast<IntegerType>(In)->getBitWidth() >
920 cast<IntegerType>(Accum)->getBitWidth())
921 Accum = In;
922 } else if (isa<PointerType>(In) && isa<PointerType>(Accum)) {
923 // Pointer unions just stay as one of the pointers.
924 } else if (isa<VectorType>(In) || isa<VectorType>(Accum)) {
925 if ((PTy = dyn_cast<VectorType>(Accum)) &&
926 PTy->getElementType() == In) {
927 // Accum is a vector, and we are accessing an element: ok.
928 } else if ((PTy = dyn_cast<VectorType>(In)) &&
929 PTy->getElementType() == Accum) {
930 // In is a vector, and accum is an element: ok, remember In.
931 Accum = In;
932 } else if ((PTy = dyn_cast<VectorType>(In)) && isa<VectorType>(Accum) &&
933 PTy->getBitWidth() == cast<VectorType>(Accum)->getBitWidth()) {
934 // Two vectors of the same size: keep Accum.
935 } else {
936 // Cannot insert an short into a <4 x int> or handle
937 // <2 x int> -> <4 x int>
938 return true;
939 }
940 } else {
941 // Pointer/FP/Integer unions merge together as integers.
942 switch (Accum->getTypeID()) {
943 case Type::PointerTyID: Accum = TD.getIntPtrType(); break;
944 case Type::FloatTyID: Accum = Type::Int32Ty; break;
945 case Type::DoubleTyID: Accum = Type::Int64Ty; break;
Dale Johannesen4c839d02007-09-28 00:21:38 +0000946 case Type::X86_FP80TyID: return true;
947 case Type::FP128TyID: return true;
948 case Type::PPC_FP128TyID: return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000949 default:
950 assert(Accum->isInteger() && "Unknown FP type!");
951 break;
952 }
953
954 switch (In->getTypeID()) {
955 case Type::PointerTyID: In = TD.getIntPtrType(); break;
956 case Type::FloatTyID: In = Type::Int32Ty; break;
957 case Type::DoubleTyID: In = Type::Int64Ty; break;
Dale Johannesen4c839d02007-09-28 00:21:38 +0000958 case Type::X86_FP80TyID: return true;
959 case Type::FP128TyID: return true;
960 case Type::PPC_FP128TyID: return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000961 default:
962 assert(In->isInteger() && "Unknown FP type!");
963 break;
964 }
965 return MergeInType(In, Accum, TD);
966 }
967 return false;
968}
969
Chris Lattner3fd59362009-01-07 06:34:28 +0000970/// getIntAtLeastAsBigAs - Return an integer type that is at least as big as the
971/// specified type. If there is no suitable type, this returns null.
972const Type *getIntAtLeastAsBigAs(unsigned NumBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000973 if (NumBits > 64) return 0;
974 if (NumBits > 32) return Type::Int64Ty;
975 if (NumBits > 16) return Type::Int32Ty;
976 if (NumBits > 8) return Type::Int16Ty;
977 return Type::Int8Ty;
978}
979
980/// CanConvertToScalar - V is a pointer. If we can convert the pointee to a
981/// single scalar integer type, return that type. Further, if the use is not
982/// a completely trivial use that mem2reg could promote, set IsNotTrivial. If
983/// there are no uses of this pointer, return Type::VoidTy to differentiate from
984/// failure.
985///
986const Type *SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial) {
987 const Type *UsedType = Type::VoidTy; // No uses, no forced type.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000988 const PointerType *PTy = cast<PointerType>(V->getType());
989
990 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
991 Instruction *User = cast<Instruction>(*UI);
992
993 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Matthijs Kooijman001006a2008-06-05 12:51:53 +0000994 // FIXME: Loads of a first class aggregrate value could be converted to a
995 // series of loads and insertvalues
996 if (!LI->getType()->isSingleValueType())
997 return 0;
998
Chris Lattner3fd59362009-01-07 06:34:28 +0000999 if (MergeInType(LI->getType(), UsedType, *TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001000 return 0;
Chris Lattner7cc97712009-01-07 06:39:58 +00001001 continue;
1002 }
1003
1004 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001005 // Storing the pointer, not into the value?
1006 if (SI->getOperand(0) == V) return 0;
Matthijs Kooijman001006a2008-06-05 12:51:53 +00001007
1008 // FIXME: Stores of a first class aggregrate value could be converted to a
1009 // series of extractvalues and stores
1010 if (!SI->getOperand(0)->getType()->isSingleValueType())
1011 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001012
1013 // NOTE: We could handle storing of FP imms into integers here!
1014
Chris Lattner3fd59362009-01-07 06:34:28 +00001015 if (MergeInType(SI->getOperand(0)->getType(), UsedType, *TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001016 return 0;
Chris Lattner7cc97712009-01-07 06:39:58 +00001017 continue;
1018 }
1019 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001020 IsNotTrivial = true;
1021 const Type *SubTy = CanConvertToScalar(CI, IsNotTrivial);
Chris Lattner3fd59362009-01-07 06:34:28 +00001022 if (!SubTy || MergeInType(SubTy, UsedType, *TD)) return 0;
Chris Lattner7cc97712009-01-07 06:39:58 +00001023 continue;
1024 }
1025
1026 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001027 // Check to see if this is stepping over an element: GEP Ptr, int C
1028 if (GEP->getNumOperands() == 2 && isa<ConstantInt>(GEP->getOperand(1))) {
1029 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
Chris Lattner3fd59362009-01-07 06:34:28 +00001030 unsigned ElSize = TD->getABITypeSize(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001031 unsigned BitOffset = Idx*ElSize*8;
1032 if (BitOffset > 64 || !isPowerOf2_32(ElSize)) return 0;
1033
1034 IsNotTrivial = true;
1035 const Type *SubElt = CanConvertToScalar(GEP, IsNotTrivial);
1036 if (SubElt == 0) return 0;
1037 if (SubElt != Type::VoidTy && SubElt->isInteger()) {
1038 const Type *NewTy =
Chris Lattner3fd59362009-01-07 06:34:28 +00001039 getIntAtLeastAsBigAs(TD->getABITypeSizeInBits(SubElt)+BitOffset);
1040 if (NewTy == 0 || MergeInType(NewTy, UsedType, *TD)) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001041 continue;
1042 }
Chris Lattner7cc97712009-01-07 06:39:58 +00001043 // Cannot handle this!
1044 return 0;
1045 }
1046
1047 if (GEP->getNumOperands() == 3 &&
1048 isa<ConstantInt>(GEP->getOperand(1)) &&
1049 isa<ConstantInt>(GEP->getOperand(2)) &&
1050 cast<ConstantInt>(GEP->getOperand(1))->isZero()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001051 // We are stepping into an element, e.g. a structure or an array:
Chris Lattner85591c62009-01-07 06:25:07 +00001052 // GEP Ptr, i32 0, i32 Cst
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001053 const Type *AggTy = PTy->getElementType();
1054 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
1055
1056 if (const ArrayType *ATy = dyn_cast<ArrayType>(AggTy)) {
1057 if (Idx >= ATy->getNumElements()) return 0; // Out of range.
1058 } else if (const VectorType *VectorTy = dyn_cast<VectorType>(AggTy)) {
1059 // Getting an element of the vector.
1060 if (Idx >= VectorTy->getNumElements()) return 0; // Out of range.
1061
1062 // Merge in the vector type.
Chris Lattner3fd59362009-01-07 06:34:28 +00001063 if (MergeInType(VectorTy, UsedType, *TD)) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001064
1065 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
1066 if (SubTy == 0) return 0;
1067
Chris Lattner3fd59362009-01-07 06:34:28 +00001068 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, *TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +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
1075 } else if (isa<StructType>(AggTy)) {
1076 // Structs are always ok.
1077 } else {
1078 return 0;
1079 }
Chris Lattner3fd59362009-01-07 06:34:28 +00001080 const Type *NTy = getIntAtLeastAsBigAs(TD->getABITypeSizeInBits(AggTy));
1081 if (NTy == 0 || MergeInType(NTy, UsedType, *TD)) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001082 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
1083 if (SubTy == 0) return 0;
Chris Lattner3fd59362009-01-07 06:34:28 +00001084 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, *TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001085 return 0;
1086 continue; // Everything looks ok
1087 }
1088 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001089 }
Chris Lattner7cc97712009-01-07 06:39:58 +00001090
1091 // Cannot handle this!
1092 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001093 }
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) {
1102 DOUT << "CONVERT TO SCALAR: " << *AI << " TYPE = "
1103 << *ActualTy << "\n";
1104 ++NumConverted;
1105
1106 BasicBlock *EntryBlock = AI->getParent();
1107 assert(EntryBlock == &EntryBlock->getParent()->getEntryBlock() &&
1108 "Not in the entry block!");
1109 EntryBlock->getInstList().remove(AI); // Take the alloca out of the program.
1110
1111 // Create and insert the alloca.
1112 AllocaInst *NewAI = new AllocaInst(ActualTy, 0, AI->getName(),
1113 EntryBlock->begin());
1114 ConvertUsesToScalar(AI, NewAI, 0);
1115 delete AI;
1116}
1117
1118
1119/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
1120/// 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.
1126void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001127 while (!Ptr->use_empty()) {
1128 Instruction *User = cast<Instruction>(Ptr->use_back());
1129
1130 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner41d58652008-02-29 07:03:13 +00001131 Value *NV = ConvertUsesOfLoadToScalar(LI, NewAI, Offset);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001132 LI->replaceAllUsesWith(NV);
1133 LI->eraseFromParent();
Chris Lattner7cc97712009-01-07 06:39:58 +00001134 continue;
1135 }
1136
1137 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001138 assert(SI->getOperand(0) != Ptr && "Consistency error!");
1139
Chris Lattner41d58652008-02-29 07:03:13 +00001140 Value *SV = ConvertUsesOfStoreToScalar(SI, NewAI, Offset);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001141 new StoreInst(SV, NewAI, SI);
1142 SI->eraseFromParent();
Chris Lattner7cc97712009-01-07 06:39:58 +00001143 continue;
1144 }
1145
1146 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Chris Lattnerb1534532008-01-30 00:39:15 +00001147 ConvertUsesToScalar(CI, NewAI, Offset);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001148 CI->eraseFromParent();
Chris Lattner7cc97712009-01-07 06:39:58 +00001149 continue;
1150 }
1151
1152 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001153 const PointerType *AggPtrTy =
1154 cast<PointerType>(GEP->getOperand(0)->getType());
Duncan Sandsae5fd622007-11-04 14:43:57 +00001155 unsigned AggSizeInBits =
Chris Lattner3fd59362009-01-07 06:34:28 +00001156 TD->getABITypeSizeInBits(AggPtrTy->getElementType());
Duncan Sandsae5fd622007-11-04 14:43:57 +00001157
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001158 // Check to see if this is stepping over an element: GEP Ptr, int C
1159 unsigned NewOffset = Offset;
1160 if (GEP->getNumOperands() == 2) {
1161 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
1162 unsigned BitOffset = Idx*AggSizeInBits;
1163
1164 NewOffset += BitOffset;
Chris Lattner7cc97712009-01-07 06:39:58 +00001165 ConvertUsesToScalar(GEP, NewAI, NewOffset);
1166 GEP->eraseFromParent();
1167 continue;
1168 }
1169
1170 assert(GEP->getNumOperands() == 3 && "Unsupported operation");
1171
1172 // We know that operand #2 is zero.
1173 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
1174 const Type *AggTy = AggPtrTy->getElementType();
1175 if (const SequentialType *SeqTy = dyn_cast<SequentialType>(AggTy)) {
1176 unsigned ElSizeBits =
1177 TD->getABITypeSizeInBits(SeqTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001178
Chris Lattner7cc97712009-01-07 06:39:58 +00001179 NewOffset += ElSizeBits*Idx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001180 } else {
Chris Lattner7cc97712009-01-07 06:39:58 +00001181 const StructType *STy = cast<StructType>(AggTy);
1182 unsigned EltBitOffset =
1183 TD->getStructLayout(STy)->getElementOffsetInBits(Idx);
1184
1185 NewOffset += EltBitOffset;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001186 }
1187 ConvertUsesToScalar(GEP, NewAI, NewOffset);
1188 GEP->eraseFromParent();
Chris Lattner7cc97712009-01-07 06:39:58 +00001189 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001190 }
Chris Lattner7cc97712009-01-07 06:39:58 +00001191
1192 assert(0 && "Unsupported operation!");
1193 abort();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001194 }
1195}
1196
Chris Lattner41d58652008-02-29 07:03:13 +00001197/// ConvertUsesOfLoadToScalar - Convert all of the users the specified load to
1198/// use the new alloca directly, returning the value that should replace the
1199/// load. This happens when we are converting an "integer union" to a
1200/// single integer scalar, or when we are converting a "vector union" to a
1201/// vector with insert/extractelement instructions.
1202///
1203/// Offset is an offset from the original alloca, in bits that need to be
1204/// shifted to the right. By the end of this, there should be no uses of Ptr.
1205Value *SROA::ConvertUsesOfLoadToScalar(LoadInst *LI, AllocaInst *NewAI,
1206 unsigned Offset) {
1207 // The load is a bit extract from NewAI shifted right by Offset bits.
1208 Value *NV = new LoadInst(NewAI, LI->getName(), LI);
1209
1210 if (NV->getType() == LI->getType() && Offset == 0) {
1211 // We win, no conversion needed.
1212 return NV;
1213 }
Chris Lattner5f062542008-02-29 07:12:06 +00001214
1215 // If the result type of the 'union' is a pointer, then this must be ptr->ptr
1216 // cast. Anything else would result in NV being an integer.
1217 if (isa<PointerType>(NV->getType())) {
1218 assert(isa<PointerType>(LI->getType()));
1219 return new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1220 }
Chris Lattner41d58652008-02-29 07:03:13 +00001221
Chris Lattner5f062542008-02-29 07:12:06 +00001222 if (const VectorType *VTy = dyn_cast<VectorType>(NV->getType())) {
Chris Lattner41d58652008-02-29 07:03:13 +00001223 // If the result alloca is a vector type, this is either an element
1224 // access or a bitcast to another vector type.
Chris Lattner5f062542008-02-29 07:12:06 +00001225 if (isa<VectorType>(LI->getType()))
1226 return new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1227
1228 // Otherwise it must be an element access.
Chris Lattner5f062542008-02-29 07:12:06 +00001229 unsigned Elt = 0;
1230 if (Offset) {
Chris Lattner3fd59362009-01-07 06:34:28 +00001231 unsigned EltSize = TD->getABITypeSizeInBits(VTy->getElementType());
Chris Lattner5f062542008-02-29 07:12:06 +00001232 Elt = Offset/EltSize;
1233 Offset -= EltSize*Elt;
Chris Lattner41d58652008-02-29 07:03:13 +00001234 }
Chris Lattner5f062542008-02-29 07:12:06 +00001235 NV = new ExtractElementInst(NV, ConstantInt::get(Type::Int32Ty, Elt),
1236 "tmp", LI);
1237
1238 // If we're done, return this element.
1239 if (NV->getType() == LI->getType() && Offset == 0)
1240 return NV;
1241 }
1242
1243 const IntegerType *NTy = cast<IntegerType>(NV->getType());
1244
1245 // If this is a big-endian system and the load is narrower than the
1246 // full alloca type, we need to do a shift to get the right bits.
1247 int ShAmt = 0;
Chris Lattner3fd59362009-01-07 06:34:28 +00001248 if (TD->isBigEndian()) {
Chris Lattner5f062542008-02-29 07:12:06 +00001249 // On big-endian machines, the lowest bit is stored at the bit offset
1250 // from the pointer given by getTypeStoreSizeInBits. This matters for
1251 // integers with a bitwidth that is not a multiple of 8.
Chris Lattner3fd59362009-01-07 06:34:28 +00001252 ShAmt = TD->getTypeStoreSizeInBits(NTy) -
1253 TD->getTypeStoreSizeInBits(LI->getType()) - Offset;
Chris Lattner5f062542008-02-29 07:12:06 +00001254 } else {
1255 ShAmt = Offset;
1256 }
1257
1258 // Note: we support negative bitwidths (with shl) which are not defined.
1259 // We do this to support (f.e.) loads off the end of a structure where
1260 // only some bits are used.
1261 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
Gabor Greifa645dd32008-05-16 19:29:10 +00001262 NV = BinaryOperator::CreateLShr(NV,
Chris Lattner5f062542008-02-29 07:12:06 +00001263 ConstantInt::get(NV->getType(),ShAmt),
1264 LI->getName(), LI);
1265 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Gabor Greifa645dd32008-05-16 19:29:10 +00001266 NV = BinaryOperator::CreateShl(NV,
Chris Lattner5f062542008-02-29 07:12:06 +00001267 ConstantInt::get(NV->getType(),-ShAmt),
1268 LI->getName(), LI);
1269
1270 // Finally, unconditionally truncate the integer to the right width.
Chris Lattner3fd59362009-01-07 06:34:28 +00001271 unsigned LIBitWidth = TD->getTypeSizeInBits(LI->getType());
Chris Lattner5f062542008-02-29 07:12:06 +00001272 if (LIBitWidth < NTy->getBitWidth())
1273 NV = new TruncInst(NV, IntegerType::get(LIBitWidth),
1274 LI->getName(), LI);
1275
1276 // If the result is an integer, this is a trunc or bitcast.
1277 if (isa<IntegerType>(LI->getType())) {
1278 // Should be done.
1279 } else if (LI->getType()->isFloatingPoint()) {
1280 // Just do a bitcast, we know the sizes match up.
Chris Lattner41d58652008-02-29 07:03:13 +00001281 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1282 } else {
Chris Lattner5f062542008-02-29 07:12:06 +00001283 // Otherwise must be a pointer.
1284 NV = new IntToPtrInst(NV, LI->getType(), LI->getName(), LI);
Chris Lattner41d58652008-02-29 07:03:13 +00001285 }
Chris Lattner5f062542008-02-29 07:12:06 +00001286 assert(NV->getType() == LI->getType() && "Didn't convert right?");
Chris Lattner41d58652008-02-29 07:03:13 +00001287 return NV;
1288}
1289
1290
1291/// ConvertUsesOfStoreToScalar - Convert the specified store to a load+store
1292/// pair of the new alloca directly, returning the value that should be stored
1293/// to the alloca. This happens when we are converting an "integer union" to a
1294/// single integer scalar, or when we are converting a "vector union" to a
1295/// vector with insert/extractelement instructions.
1296///
1297/// Offset is an offset from the original alloca, in bits that need to be
1298/// shifted to the right. By the end of this, there should be no uses of Ptr.
1299Value *SROA::ConvertUsesOfStoreToScalar(StoreInst *SI, AllocaInst *NewAI,
1300 unsigned Offset) {
1301
1302 // Convert the stored type to the actual type, shift it left to insert
1303 // then 'or' into place.
1304 Value *SV = SI->getOperand(0);
1305 const Type *AllocaType = NewAI->getType()->getElementType();
1306 if (SV->getType() == AllocaType && Offset == 0) {
1307 // All is well.
1308 } else if (const VectorType *PTy = dyn_cast<VectorType>(AllocaType)) {
1309 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1310
1311 // If the result alloca is a vector type, this is either an element
1312 // access or a bitcast to another vector type.
1313 if (isa<VectorType>(SV->getType())) {
1314 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1315 } else {
1316 // Must be an element insertion.
Chris Lattner3fd59362009-01-07 06:34:28 +00001317 unsigned Elt = Offset/TD->getABITypeSizeInBits(PTy->getElementType());
Gabor Greifd6da1d02008-04-06 20:25:17 +00001318 SV = InsertElementInst::Create(Old, SV,
1319 ConstantInt::get(Type::Int32Ty, Elt),
1320 "tmp", SI);
Chris Lattner41d58652008-02-29 07:03:13 +00001321 }
1322 } else if (isa<PointerType>(AllocaType)) {
1323 // If the alloca type is a pointer, then all the elements must be
1324 // pointers.
1325 if (SV->getType() != AllocaType)
1326 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1327 } else {
1328 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1329
1330 // If SV is a float, convert it to the appropriate integer type.
1331 // If it is a pointer, do the same, and also handle ptr->ptr casts
1332 // here.
Chris Lattner3fd59362009-01-07 06:34:28 +00001333 unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1334 unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1335 unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1336 unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
Chris Lattner41d58652008-02-29 07:03:13 +00001337 if (SV->getType()->isFloatingPoint())
1338 SV = new BitCastInst(SV, IntegerType::get(SrcWidth),
1339 SV->getName(), SI);
1340 else if (isa<PointerType>(SV->getType()))
Chris Lattner3fd59362009-01-07 06:34:28 +00001341 SV = new PtrToIntInst(SV, TD->getIntPtrType(), SV->getName(), SI);
Chris Lattner41d58652008-02-29 07:03:13 +00001342
1343 // Always zero extend the value if needed.
1344 if (SV->getType() != AllocaType)
1345 SV = new ZExtInst(SV, AllocaType, SV->getName(), SI);
1346
1347 // If this is a big-endian system and the store is narrower than the
1348 // full alloca type, we need to do a shift to get the right bits.
1349 int ShAmt = 0;
Chris Lattner3fd59362009-01-07 06:34:28 +00001350 if (TD->isBigEndian()) {
Chris Lattner41d58652008-02-29 07:03:13 +00001351 // On big-endian machines, the lowest bit is stored at the bit offset
1352 // from the pointer given by getTypeStoreSizeInBits. This matters for
1353 // integers with a bitwidth that is not a multiple of 8.
1354 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
1355 } else {
1356 ShAmt = Offset;
1357 }
1358
1359 // Note: we support negative bitwidths (with shr) which are not defined.
1360 // We do this to support (f.e.) stores off the end of a structure where
1361 // only some bits in the structure are set.
1362 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1363 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
Gabor Greifa645dd32008-05-16 19:29:10 +00001364 SV = BinaryOperator::CreateShl(SV,
Chris Lattner41d58652008-02-29 07:03:13 +00001365 ConstantInt::get(SV->getType(), ShAmt),
1366 SV->getName(), SI);
1367 Mask <<= ShAmt;
1368 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
Gabor Greifa645dd32008-05-16 19:29:10 +00001369 SV = BinaryOperator::CreateLShr(SV,
Chris Lattner41d58652008-02-29 07:03:13 +00001370 ConstantInt::get(SV->getType(),-ShAmt),
1371 SV->getName(), SI);
1372 Mask = Mask.lshr(ShAmt);
1373 }
1374
1375 // Mask out the bits we are about to insert from the old value, and or
1376 // in the new bits.
1377 if (SrcWidth != DestWidth) {
1378 assert(DestWidth > SrcWidth);
Gabor Greifa645dd32008-05-16 19:29:10 +00001379 Old = BinaryOperator::CreateAnd(Old, ConstantInt::get(~Mask),
Chris Lattner41d58652008-02-29 07:03:13 +00001380 Old->getName()+".mask", SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00001381 SV = BinaryOperator::CreateOr(Old, SV, SV->getName()+".ins", SI);
Chris Lattner41d58652008-02-29 07:03:13 +00001382 }
1383 }
1384 return SV;
1385}
1386
1387
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001388
1389/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1390/// some part of a constant global variable. This intentionally only accepts
1391/// constant expressions because we don't can't rewrite arbitrary instructions.
1392static bool PointsToConstantGlobal(Value *V) {
1393 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1394 return GV->isConstant();
1395 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1396 if (CE->getOpcode() == Instruction::BitCast ||
1397 CE->getOpcode() == Instruction::GetElementPtr)
1398 return PointsToConstantGlobal(CE->getOperand(0));
1399 return false;
1400}
1401
1402/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1403/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1404/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1405/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1406/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1407/// the alloca, and if the source pointer is a pointer to a constant global, we
1408/// can optimize this.
1409static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1410 bool isOffset) {
1411 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1412 if (isa<LoadInst>(*UI)) {
1413 // Ignore loads, they are always ok.
1414 continue;
1415 }
1416 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1417 // If uses of the bitcast are ok, we are ok.
1418 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1419 return false;
1420 continue;
1421 }
1422 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1423 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1424 // doesn't, it does.
1425 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1426 isOffset || !GEP->hasAllZeroIndices()))
1427 return false;
1428 continue;
1429 }
1430
1431 // If this is isn't our memcpy/memmove, reject it as something we can't
1432 // handle.
1433 if (!isa<MemCpyInst>(*UI) && !isa<MemMoveInst>(*UI))
1434 return false;
1435
1436 // If we already have seen a copy, reject the second one.
1437 if (TheCopy) return false;
1438
1439 // If the pointer has been offset from the start of the alloca, we can't
1440 // safely handle this.
1441 if (isOffset) return false;
1442
1443 // If the memintrinsic isn't using the alloca as the dest, reject it.
1444 if (UI.getOperandNo() != 1) return false;
1445
1446 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1447
1448 // If the source of the memcpy/move is not a constant global, reject it.
1449 if (!PointsToConstantGlobal(MI->getOperand(2)))
1450 return false;
1451
1452 // Otherwise, the transform is safe. Remember the copy instruction.
1453 TheCopy = MI;
1454 }
1455 return true;
1456}
1457
1458/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1459/// modified by a copy from a constant global. If we can prove this, we can
1460/// replace any uses of the alloca with uses of the global directly.
1461Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocationInst *AI) {
1462 Instruction *TheCopy = 0;
1463 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1464 return TheCopy;
1465 return 0;
1466}