1 //===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
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 they
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 #include "llvm/Transforms/Scalar.h"
23 #include "llvm/ADT/SetVector.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Analysis/AssumptionCache.h"
27 #include "llvm/Analysis/Loads.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/IR/CallSite.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/DIBuilder.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/DebugInfo.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/Dominators.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/GetElementPtrTypeIterator.h"
38 #include "llvm/IR/GlobalVariable.h"
39 #include "llvm/IR/IRBuilder.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/IntrinsicInst.h"
42 #include "llvm/IR/LLVMContext.h"
43 #include "llvm/IR/Module.h"
44 #include "llvm/IR/Operator.h"
45 #include "llvm/Pass.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Transforms/Utils/Local.h"
51 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
52 #include "llvm/Transforms/Utils/SSAUpdater.h"
53 using namespace llvm;
54
55 #define DEBUG_TYPE "scalarrepl"
56
57 STATISTIC(NumReplaced, "Number of allocas broken up");
58 STATISTIC(NumPromoted, "Number of allocas promoted");
59 STATISTIC(NumAdjusted, "Number of scalar allocas adjusted to allow promotion");
60 STATISTIC(NumConverted, "Number of aggregates converted to scalar");
61
62 namespace {
63 struct SROA : public FunctionPass {
SROA__anon47fa93a10111::SROA64 SROA(int T, bool hasDT, char &ID, int ST, int AT, int SLT)
65 : FunctionPass(ID), HasDomTree(hasDT) {
66 if (T == -1)
67 SRThreshold = 128;
68 else
69 SRThreshold = T;
70 if (ST == -1)
71 StructMemberThreshold = 32;
72 else
73 StructMemberThreshold = ST;
74 if (AT == -1)
75 ArrayElementThreshold = 8;
76 else
77 ArrayElementThreshold = AT;
78 if (SLT == -1)
79 // Do not limit the scalar integer load size if no threshold is given.
80 ScalarLoadThreshold = -1;
81 else
82 ScalarLoadThreshold = SLT;
83 }
84
85 bool runOnFunction(Function &F) override;
86
87 bool performScalarRepl(Function &F);
88 bool performPromotion(Function &F);
89
90 private:
91 bool HasDomTree;
92 const DataLayout *DL;
93
94 /// DeadInsts - Keep track of instructions we have made dead, so that
95 /// we can remove them after we are done working.
96 SmallVector<Value*, 32> DeadInsts;
97
98 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
99 /// information about the uses. All these fields are initialized to false
100 /// and set to true when something is learned.
101 struct AllocaInfo {
102 /// The alloca to promote.
103 AllocaInst *AI;
104
105 /// CheckedPHIs - This is a set of verified PHI nodes, to prevent infinite
106 /// looping and avoid redundant work.
107 SmallPtrSet<PHINode*, 8> CheckedPHIs;
108
109 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
110 bool isUnsafe : 1;
111
112 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
113 bool isMemCpySrc : 1;
114
115 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
116 bool isMemCpyDst : 1;
117
118 /// hasSubelementAccess - This is true if a subelement of the alloca is
119 /// ever accessed, or false if the alloca is only accessed with mem
120 /// intrinsics or load/store that only access the entire alloca at once.
121 bool hasSubelementAccess : 1;
122
123 /// hasALoadOrStore - This is true if there are any loads or stores to it.
124 /// The alloca may just be accessed with memcpy, for example, which would
125 /// not set this.
126 bool hasALoadOrStore : 1;
127
AllocaInfo__anon47fa93a10111::SROA::AllocaInfo128 explicit AllocaInfo(AllocaInst *ai)
129 : AI(ai), isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
130 hasSubelementAccess(false), hasALoadOrStore(false) {}
131 };
132
133 /// SRThreshold - The maximum alloca size to considered for SROA.
134 unsigned SRThreshold;
135
136 /// StructMemberThreshold - The maximum number of members a struct can
137 /// contain to be considered for SROA.
138 unsigned StructMemberThreshold;
139
140 /// ArrayElementThreshold - The maximum number of elements an array can
141 /// have to be considered for SROA.
142 unsigned ArrayElementThreshold;
143
144 /// ScalarLoadThreshold - The maximum size in bits of scalars to load when
145 /// converting to scalar
146 unsigned ScalarLoadThreshold;
147
MarkUnsafe__anon47fa93a10111::SROA148 void MarkUnsafe(AllocaInfo &I, Instruction *User) {
149 I.isUnsafe = true;
150 DEBUG(dbgs() << " Transformation preventing inst: " << *User << '\n');
151 }
152
153 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
154
155 void isSafeForScalarRepl(Instruction *I, uint64_t Offset, AllocaInfo &Info);
156 void isSafePHISelectUseForScalarRepl(Instruction *User, uint64_t Offset,
157 AllocaInfo &Info);
158 void isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset, AllocaInfo &Info);
159 void isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
160 Type *MemOpType, bool isStore, AllocaInfo &Info,
161 Instruction *TheAccess, bool AllowWholeAccess);
162 bool TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size);
163 uint64_t FindElementAndOffset(Type *&T, uint64_t &Offset,
164 Type *&IdxTy);
165
166 void DoScalarReplacement(AllocaInst *AI,
167 std::vector<AllocaInst*> &WorkList);
168 void DeleteDeadInstructions();
169
170 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
171 SmallVectorImpl<AllocaInst *> &NewElts);
172 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
173 SmallVectorImpl<AllocaInst *> &NewElts);
174 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
175 SmallVectorImpl<AllocaInst *> &NewElts);
176 void RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
177 uint64_t Offset,
178 SmallVectorImpl<AllocaInst *> &NewElts);
179 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
180 AllocaInst *AI,
181 SmallVectorImpl<AllocaInst *> &NewElts);
182 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
183 SmallVectorImpl<AllocaInst *> &NewElts);
184 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
185 SmallVectorImpl<AllocaInst *> &NewElts);
186 bool ShouldAttemptScalarRepl(AllocaInst *AI);
187 };
188
189 // SROA_DT - SROA that uses DominatorTree.
190 struct SROA_DT : public SROA {
191 static char ID;
192 public:
SROA_DT__anon47fa93a10111::SROA_DT193 SROA_DT(int T = -1, int ST = -1, int AT = -1, int SLT = -1) :
194 SROA(T, true, ID, ST, AT, SLT) {
195 initializeSROA_DTPass(*PassRegistry::getPassRegistry());
196 }
197
198 // getAnalysisUsage - This pass does not require any passes, but we know it
199 // will not alter the CFG, so say so.
getAnalysisUsage__anon47fa93a10111::SROA_DT200 void getAnalysisUsage(AnalysisUsage &AU) const override {
201 AU.addRequired<AssumptionCacheTracker>();
202 AU.addRequired<DominatorTreeWrapperPass>();
203 AU.setPreservesCFG();
204 }
205 };
206
207 // SROA_SSAUp - SROA that uses SSAUpdater.
208 struct SROA_SSAUp : public SROA {
209 static char ID;
210 public:
SROA_SSAUp__anon47fa93a10111::SROA_SSAUp211 SROA_SSAUp(int T = -1, int ST = -1, int AT = -1, int SLT = -1) :
212 SROA(T, false, ID, ST, AT, SLT) {
213 initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
214 }
215
216 // getAnalysisUsage - This pass does not require any passes, but we know it
217 // will not alter the CFG, so say so.
getAnalysisUsage__anon47fa93a10111::SROA_SSAUp218 void getAnalysisUsage(AnalysisUsage &AU) const override {
219 AU.addRequired<AssumptionCacheTracker>();
220 AU.setPreservesCFG();
221 }
222 };
223
224 }
225
226 char SROA_DT::ID = 0;
227 char SROA_SSAUp::ID = 0;
228
229 INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl",
230 "Scalar Replacement of Aggregates (DT)", false, false)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)231 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
232 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
233 INITIALIZE_PASS_END(SROA_DT, "scalarrepl",
234 "Scalar Replacement of Aggregates (DT)", false, false)
235
236 INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
237 "Scalar Replacement of Aggregates (SSAUp)", false, false)
238 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
239 INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
240 "Scalar Replacement of Aggregates (SSAUp)", false, false)
241
242 // Public interface to the ScalarReplAggregates pass
243 FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
244 bool UseDomTree,
245 int StructMemberThreshold,
246 int ArrayElementThreshold,
247 int ScalarLoadThreshold) {
248 if (UseDomTree)
249 return new SROA_DT(Threshold, StructMemberThreshold, ArrayElementThreshold,
250 ScalarLoadThreshold);
251 return new SROA_SSAUp(Threshold, StructMemberThreshold,
252 ArrayElementThreshold, ScalarLoadThreshold);
253 }
254
255
256 //===----------------------------------------------------------------------===//
257 // Convert To Scalar Optimization.
258 //===----------------------------------------------------------------------===//
259
260 namespace {
261 /// ConvertToScalarInfo - This class implements the "Convert To Scalar"
262 /// optimization, which scans the uses of an alloca and determines if it can
263 /// rewrite it in terms of a single new alloca that can be mem2reg'd.
264 class ConvertToScalarInfo {
265 /// AllocaSize - The size of the alloca being considered in bytes.
266 unsigned AllocaSize;
267 const DataLayout &DL;
268 unsigned ScalarLoadThreshold;
269
270 /// IsNotTrivial - This is set to true if there is some access to the object
271 /// which means that mem2reg can't promote it.
272 bool IsNotTrivial;
273
274 /// ScalarKind - Tracks the kind of alloca being considered for promotion,
275 /// computed based on the uses of the alloca rather than the LLVM type system.
276 enum {
277 Unknown,
278
279 // Accesses via GEPs that are consistent with element access of a vector
280 // type. This will not be converted into a vector unless there is a later
281 // access using an actual vector type.
282 ImplicitVector,
283
284 // Accesses via vector operations and GEPs that are consistent with the
285 // layout of a vector type.
286 Vector,
287
288 // An integer bag-of-bits with bitwise operations for insertion and
289 // extraction. Any combination of types can be converted into this kind
290 // of scalar.
291 Integer
292 } ScalarKind;
293
294 /// VectorTy - This tracks the type that we should promote the vector to if
295 /// it is possible to turn it into a vector. This starts out null, and if it
296 /// isn't possible to turn into a vector type, it gets set to VoidTy.
297 VectorType *VectorTy;
298
299 /// HadNonMemTransferAccess - True if there is at least one access to the
300 /// alloca that is not a MemTransferInst. We don't want to turn structs into
301 /// large integers unless there is some potential for optimization.
302 bool HadNonMemTransferAccess;
303
304 /// HadDynamicAccess - True if some element of this alloca was dynamic.
305 /// We don't yet have support for turning a dynamic access into a large
306 /// integer.
307 bool HadDynamicAccess;
308
309 public:
ConvertToScalarInfo(unsigned Size,const DataLayout & DL,unsigned SLT)310 explicit ConvertToScalarInfo(unsigned Size, const DataLayout &DL,
311 unsigned SLT)
312 : AllocaSize(Size), DL(DL), ScalarLoadThreshold(SLT), IsNotTrivial(false),
313 ScalarKind(Unknown), VectorTy(nullptr), HadNonMemTransferAccess(false),
314 HadDynamicAccess(false) { }
315
316 AllocaInst *TryConvert(AllocaInst *AI);
317
318 private:
319 bool CanConvertToScalar(Value *V, uint64_t Offset, Value* NonConstantIdx);
320 void MergeInTypeForLoadOrStore(Type *In, uint64_t Offset);
321 bool MergeInVectorType(VectorType *VInTy, uint64_t Offset);
322 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset,
323 Value *NonConstantIdx);
324
325 Value *ConvertScalar_ExtractValue(Value *NV, Type *ToType,
326 uint64_t Offset, Value* NonConstantIdx,
327 IRBuilder<> &Builder);
328 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
329 uint64_t Offset, Value* NonConstantIdx,
330 IRBuilder<> &Builder);
331 };
332 } // end anonymous namespace.
333
334
335 /// TryConvert - Analyze the specified alloca, and if it is safe to do so,
336 /// rewrite it to be a new alloca which is mem2reg'able. This returns the new
337 /// alloca if possible or null if not.
TryConvert(AllocaInst * AI)338 AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
339 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
340 // out.
341 if (!CanConvertToScalar(AI, 0, nullptr) || !IsNotTrivial)
342 return nullptr;
343
344 // If an alloca has only memset / memcpy uses, it may still have an Unknown
345 // ScalarKind. Treat it as an Integer below.
346 if (ScalarKind == Unknown)
347 ScalarKind = Integer;
348
349 if (ScalarKind == Vector && VectorTy->getBitWidth() != AllocaSize * 8)
350 ScalarKind = Integer;
351
352 // If we were able to find a vector type that can handle this with
353 // insert/extract elements, and if there was at least one use that had
354 // a vector type, promote this to a vector. We don't want to promote
355 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
356 // we just get a lot of insert/extracts. If at least one vector is
357 // involved, then we probably really do have a union of vector/array.
358 Type *NewTy;
359 if (ScalarKind == Vector) {
360 assert(VectorTy && "Missing type for vector scalar.");
361 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
362 << *VectorTy << '\n');
363 NewTy = VectorTy; // Use the vector type.
364 } else {
365 unsigned BitWidth = AllocaSize * 8;
366
367 // Do not convert to scalar integer if the alloca size exceeds the
368 // scalar load threshold.
369 if (BitWidth > ScalarLoadThreshold)
370 return nullptr;
371
372 if ((ScalarKind == ImplicitVector || ScalarKind == Integer) &&
373 !HadNonMemTransferAccess && !DL.fitsInLegalInteger(BitWidth))
374 return nullptr;
375 // Dynamic accesses on integers aren't yet supported. They need us to shift
376 // by a dynamic amount which could be difficult to work out as we might not
377 // know whether to use a left or right shift.
378 if (ScalarKind == Integer && HadDynamicAccess)
379 return nullptr;
380
381 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
382 // Create and insert the integer alloca.
383 NewTy = IntegerType::get(AI->getContext(), BitWidth);
384 }
385 AllocaInst *NewAI = new AllocaInst(NewTy, nullptr, "",
386 AI->getParent()->begin());
387 ConvertUsesToScalar(AI, NewAI, 0, nullptr);
388 return NewAI;
389 }
390
391 /// MergeInTypeForLoadOrStore - Add the 'In' type to the accumulated vector type
392 /// (VectorTy) so far at the offset specified by Offset (which is specified in
393 /// bytes).
394 ///
395 /// There are two cases we handle here:
396 /// 1) A union of vector types of the same size and potentially its elements.
397 /// Here we turn element accesses into insert/extract element operations.
398 /// This promotes a <4 x float> with a store of float to the third element
399 /// into a <4 x float> that uses insert element.
400 /// 2) A fully general blob of memory, which we turn into some (potentially
401 /// large) integer type with extract and insert operations where the loads
402 /// and stores would mutate the memory. We mark this by setting VectorTy
403 /// to VoidTy.
MergeInTypeForLoadOrStore(Type * In,uint64_t Offset)404 void ConvertToScalarInfo::MergeInTypeForLoadOrStore(Type *In,
405 uint64_t Offset) {
406 // If we already decided to turn this into a blob of integer memory, there is
407 // nothing to be done.
408 if (ScalarKind == Integer)
409 return;
410
411 // If this could be contributing to a vector, analyze it.
412
413 // If the In type is a vector that is the same size as the alloca, see if it
414 // matches the existing VecTy.
415 if (VectorType *VInTy = dyn_cast<VectorType>(In)) {
416 if (MergeInVectorType(VInTy, Offset))
417 return;
418 } else if (In->isFloatTy() || In->isDoubleTy() ||
419 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
420 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
421 // Full width accesses can be ignored, because they can always be turned
422 // into bitcasts.
423 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
424 if (EltSize == AllocaSize)
425 return;
426
427 // If we're accessing something that could be an element of a vector, see
428 // if the implied vector agrees with what we already have and if Offset is
429 // compatible with it.
430 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
431 (!VectorTy || EltSize == VectorTy->getElementType()
432 ->getPrimitiveSizeInBits()/8)) {
433 if (!VectorTy) {
434 ScalarKind = ImplicitVector;
435 VectorTy = VectorType::get(In, AllocaSize/EltSize);
436 }
437 return;
438 }
439 }
440
441 // Otherwise, we have a case that we can't handle with an optimized vector
442 // form. We can still turn this into a large integer.
443 ScalarKind = Integer;
444 }
445
446 /// MergeInVectorType - Handles the vector case of MergeInTypeForLoadOrStore,
447 /// returning true if the type was successfully merged and false otherwise.
MergeInVectorType(VectorType * VInTy,uint64_t Offset)448 bool ConvertToScalarInfo::MergeInVectorType(VectorType *VInTy,
449 uint64_t Offset) {
450 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
451 // If we're storing/loading a vector of the right size, allow it as a
452 // vector. If this the first vector we see, remember the type so that
453 // we know the element size. If this is a subsequent access, ignore it
454 // even if it is a differing type but the same size. Worst case we can
455 // bitcast the resultant vectors.
456 if (!VectorTy)
457 VectorTy = VInTy;
458 ScalarKind = Vector;
459 return true;
460 }
461
462 return false;
463 }
464
465 /// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
466 /// its accesses to a single vector type, return true and set VecTy to
467 /// the new type. If we could convert the alloca into a single promotable
468 /// integer, return true but set VecTy to VoidTy. Further, if the use is not a
469 /// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
470 /// is the current offset from the base of the alloca being analyzed.
471 ///
472 /// If we see at least one access to the value that is as a vector type, set the
473 /// SawVec flag.
CanConvertToScalar(Value * V,uint64_t Offset,Value * NonConstantIdx)474 bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset,
475 Value* NonConstantIdx) {
476 for (User *U : V->users()) {
477 Instruction *UI = cast<Instruction>(U);
478
479 if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
480 // Don't break volatile loads.
481 if (!LI->isSimple())
482 return false;
483 // Don't touch MMX operations.
484 if (LI->getType()->isX86_MMXTy())
485 return false;
486 HadNonMemTransferAccess = true;
487 MergeInTypeForLoadOrStore(LI->getType(), Offset);
488 continue;
489 }
490
491 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
492 // Storing the pointer, not into the value?
493 if (SI->getOperand(0) == V || !SI->isSimple()) return false;
494 // Don't touch MMX operations.
495 if (SI->getOperand(0)->getType()->isX86_MMXTy())
496 return false;
497 HadNonMemTransferAccess = true;
498 MergeInTypeForLoadOrStore(SI->getOperand(0)->getType(), Offset);
499 continue;
500 }
501
502 if (BitCastInst *BCI = dyn_cast<BitCastInst>(UI)) {
503 if (!onlyUsedByLifetimeMarkers(BCI))
504 IsNotTrivial = true; // Can't be mem2reg'd.
505 if (!CanConvertToScalar(BCI, Offset, NonConstantIdx))
506 return false;
507 continue;
508 }
509
510 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UI)) {
511 // If this is a GEP with a variable indices, we can't handle it.
512 PointerType* PtrTy = dyn_cast<PointerType>(GEP->getPointerOperandType());
513 if (!PtrTy)
514 return false;
515
516 // Compute the offset that this GEP adds to the pointer.
517 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
518 Value *GEPNonConstantIdx = nullptr;
519 if (!GEP->hasAllConstantIndices()) {
520 if (!isa<VectorType>(PtrTy->getElementType()))
521 return false;
522 if (NonConstantIdx)
523 return false;
524 GEPNonConstantIdx = Indices.pop_back_val();
525 if (!GEPNonConstantIdx->getType()->isIntegerTy(32))
526 return false;
527 HadDynamicAccess = true;
528 } else
529 GEPNonConstantIdx = NonConstantIdx;
530 uint64_t GEPOffset = DL.getIndexedOffset(PtrTy,
531 Indices);
532 // See if all uses can be converted.
533 if (!CanConvertToScalar(GEP, Offset+GEPOffset, GEPNonConstantIdx))
534 return false;
535 IsNotTrivial = true; // Can't be mem2reg'd.
536 HadNonMemTransferAccess = true;
537 continue;
538 }
539
540 // If this is a constant sized memset of a constant value (e.g. 0) we can
541 // handle it.
542 if (MemSetInst *MSI = dyn_cast<MemSetInst>(UI)) {
543 // Store to dynamic index.
544 if (NonConstantIdx)
545 return false;
546 // Store of constant value.
547 if (!isa<ConstantInt>(MSI->getValue()))
548 return false;
549
550 // Store of constant size.
551 ConstantInt *Len = dyn_cast<ConstantInt>(MSI->getLength());
552 if (!Len)
553 return false;
554
555 // If the size differs from the alloca, we can only convert the alloca to
556 // an integer bag-of-bits.
557 // FIXME: This should handle all of the cases that are currently accepted
558 // as vector element insertions.
559 if (Len->getZExtValue() != AllocaSize || Offset != 0)
560 ScalarKind = Integer;
561
562 IsNotTrivial = true; // Can't be mem2reg'd.
563 HadNonMemTransferAccess = true;
564 continue;
565 }
566
567 // If this is a memcpy or memmove into or out of the whole allocation, we
568 // can handle it like a load or store of the scalar type.
569 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(UI)) {
570 // Store to dynamic index.
571 if (NonConstantIdx)
572 return false;
573 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
574 if (!Len || Len->getZExtValue() != AllocaSize || Offset != 0)
575 return false;
576
577 IsNotTrivial = true; // Can't be mem2reg'd.
578 continue;
579 }
580
581 // If this is a lifetime intrinsic, we can handle it.
582 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(UI)) {
583 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
584 II->getIntrinsicID() == Intrinsic::lifetime_end) {
585 continue;
586 }
587 }
588
589 // Otherwise, we cannot handle this!
590 return false;
591 }
592
593 return true;
594 }
595
596 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
597 /// directly. This happens when we are converting an "integer union" to a
598 /// single integer scalar, or when we are converting a "vector union" to a
599 /// vector with insert/extractelement instructions.
600 ///
601 /// Offset is an offset from the original alloca, in bits that need to be
602 /// shifted to the right. By the end of this, there should be no uses of Ptr.
ConvertUsesToScalar(Value * Ptr,AllocaInst * NewAI,uint64_t Offset,Value * NonConstantIdx)603 void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
604 uint64_t Offset,
605 Value* NonConstantIdx) {
606 while (!Ptr->use_empty()) {
607 Instruction *User = cast<Instruction>(Ptr->user_back());
608
609 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
610 ConvertUsesToScalar(CI, NewAI, Offset, NonConstantIdx);
611 CI->eraseFromParent();
612 continue;
613 }
614
615 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
616 // Compute the offset that this GEP adds to the pointer.
617 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
618 Value* GEPNonConstantIdx = nullptr;
619 if (!GEP->hasAllConstantIndices()) {
620 assert(!NonConstantIdx &&
621 "Dynamic GEP reading from dynamic GEP unsupported");
622 GEPNonConstantIdx = Indices.pop_back_val();
623 } else
624 GEPNonConstantIdx = NonConstantIdx;
625 uint64_t GEPOffset = DL.getIndexedOffset(GEP->getPointerOperandType(),
626 Indices);
627 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8, GEPNonConstantIdx);
628 GEP->eraseFromParent();
629 continue;
630 }
631
632 IRBuilder<> Builder(User);
633
634 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
635 // The load is a bit extract from NewAI shifted right by Offset bits.
636 Value *LoadedVal = Builder.CreateLoad(NewAI);
637 Value *NewLoadVal
638 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset,
639 NonConstantIdx, Builder);
640 LI->replaceAllUsesWith(NewLoadVal);
641 LI->eraseFromParent();
642 continue;
643 }
644
645 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
646 assert(SI->getOperand(0) != Ptr && "Consistency error!");
647 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
648 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
649 NonConstantIdx, Builder);
650 Builder.CreateStore(New, NewAI);
651 SI->eraseFromParent();
652
653 // If the load we just inserted is now dead, then the inserted store
654 // overwrote the entire thing.
655 if (Old->use_empty())
656 Old->eraseFromParent();
657 continue;
658 }
659
660 // If this is a constant sized memset of a constant value (e.g. 0) we can
661 // transform it into a store of the expanded constant value.
662 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
663 assert(MSI->getRawDest() == Ptr && "Consistency error!");
664 assert(!NonConstantIdx && "Cannot replace dynamic memset with insert");
665 int64_t SNumBytes = cast<ConstantInt>(MSI->getLength())->getSExtValue();
666 if (SNumBytes > 0 && (SNumBytes >> 32) == 0) {
667 unsigned NumBytes = static_cast<unsigned>(SNumBytes);
668 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
669
670 // Compute the value replicated the right number of times.
671 APInt APVal(NumBytes*8, Val);
672
673 // Splat the value if non-zero.
674 if (Val)
675 for (unsigned i = 1; i != NumBytes; ++i)
676 APVal |= APVal << 8;
677
678 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
679 Value *New = ConvertScalar_InsertValue(
680 ConstantInt::get(User->getContext(), APVal),
681 Old, Offset, nullptr, Builder);
682 Builder.CreateStore(New, NewAI);
683
684 // If the load we just inserted is now dead, then the memset overwrote
685 // the entire thing.
686 if (Old->use_empty())
687 Old->eraseFromParent();
688 }
689 MSI->eraseFromParent();
690 continue;
691 }
692
693 // If this is a memcpy or memmove into or out of the whole allocation, we
694 // can handle it like a load or store of the scalar type.
695 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
696 assert(Offset == 0 && "must be store to start of alloca");
697 assert(!NonConstantIdx && "Cannot replace dynamic transfer with insert");
698
699 // If the source and destination are both to the same alloca, then this is
700 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
701 // as appropriate.
702 AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, &DL, 0));
703
704 if (GetUnderlyingObject(MTI->getSource(), &DL, 0) != OrigAI) {
705 // Dest must be OrigAI, change this to be a load from the original
706 // pointer (bitcasted), then a store to our new alloca.
707 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
708 Value *SrcPtr = MTI->getSource();
709 PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
710 PointerType* AIPTy = cast<PointerType>(NewAI->getType());
711 if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
712 AIPTy = PointerType::get(AIPTy->getElementType(),
713 SPTy->getAddressSpace());
714 }
715 SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
716
717 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
718 SrcVal->setAlignment(MTI->getAlignment());
719 Builder.CreateStore(SrcVal, NewAI);
720 } else if (GetUnderlyingObject(MTI->getDest(), &DL, 0) != OrigAI) {
721 // Src must be OrigAI, change this to be a load from NewAI then a store
722 // through the original dest pointer (bitcasted).
723 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
724 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
725
726 PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
727 PointerType* AIPTy = cast<PointerType>(NewAI->getType());
728 if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
729 AIPTy = PointerType::get(AIPTy->getElementType(),
730 DPTy->getAddressSpace());
731 }
732 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
733
734 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
735 NewStore->setAlignment(MTI->getAlignment());
736 } else {
737 // Noop transfer. Src == Dst
738 }
739
740 MTI->eraseFromParent();
741 continue;
742 }
743
744 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
745 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
746 II->getIntrinsicID() == Intrinsic::lifetime_end) {
747 // There's no need to preserve these, as the resulting alloca will be
748 // converted to a register anyways.
749 II->eraseFromParent();
750 continue;
751 }
752 }
753
754 llvm_unreachable("Unsupported operation!");
755 }
756 }
757
758 /// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
759 /// or vector value FromVal, extracting the bits from the offset specified by
760 /// Offset. This returns the value, which is of type ToType.
761 ///
762 /// This happens when we are converting an "integer union" to a single
763 /// integer scalar, or when we are converting a "vector union" to a vector with
764 /// insert/extractelement instructions.
765 ///
766 /// Offset is an offset from the original alloca, in bits that need to be
767 /// shifted to the right.
768 Value *ConvertToScalarInfo::
ConvertScalar_ExtractValue(Value * FromVal,Type * ToType,uint64_t Offset,Value * NonConstantIdx,IRBuilder<> & Builder)769 ConvertScalar_ExtractValue(Value *FromVal, Type *ToType,
770 uint64_t Offset, Value* NonConstantIdx,
771 IRBuilder<> &Builder) {
772 // If the load is of the whole new alloca, no conversion is needed.
773 Type *FromType = FromVal->getType();
774 if (FromType == ToType && Offset == 0)
775 return FromVal;
776
777 // If the result alloca is a vector type, this is either an element
778 // access or a bitcast to another vector type of the same size.
779 if (VectorType *VTy = dyn_cast<VectorType>(FromType)) {
780 unsigned FromTypeSize = DL.getTypeAllocSize(FromType);
781 unsigned ToTypeSize = DL.getTypeAllocSize(ToType);
782 if (FromTypeSize == ToTypeSize)
783 return Builder.CreateBitCast(FromVal, ToType);
784
785 // Otherwise it must be an element access.
786 unsigned Elt = 0;
787 if (Offset) {
788 unsigned EltSize = DL.getTypeAllocSizeInBits(VTy->getElementType());
789 Elt = Offset/EltSize;
790 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
791 }
792 // Return the element extracted out of it.
793 Value *Idx;
794 if (NonConstantIdx) {
795 if (Elt)
796 Idx = Builder.CreateAdd(NonConstantIdx,
797 Builder.getInt32(Elt),
798 "dyn.offset");
799 else
800 Idx = NonConstantIdx;
801 } else
802 Idx = Builder.getInt32(Elt);
803 Value *V = Builder.CreateExtractElement(FromVal, Idx);
804 if (V->getType() != ToType)
805 V = Builder.CreateBitCast(V, ToType);
806 return V;
807 }
808
809 // If ToType is a first class aggregate, extract out each of the pieces and
810 // use insertvalue's to form the FCA.
811 if (StructType *ST = dyn_cast<StructType>(ToType)) {
812 assert(!NonConstantIdx &&
813 "Dynamic indexing into struct types not supported");
814 const StructLayout &Layout = *DL.getStructLayout(ST);
815 Value *Res = UndefValue::get(ST);
816 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
817 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
818 Offset+Layout.getElementOffsetInBits(i),
819 nullptr, Builder);
820 Res = Builder.CreateInsertValue(Res, Elt, i);
821 }
822 return Res;
823 }
824
825 if (ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
826 assert(!NonConstantIdx &&
827 "Dynamic indexing into array types not supported");
828 uint64_t EltSize = DL.getTypeAllocSizeInBits(AT->getElementType());
829 Value *Res = UndefValue::get(AT);
830 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
831 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
832 Offset+i*EltSize, nullptr,
833 Builder);
834 Res = Builder.CreateInsertValue(Res, Elt, i);
835 }
836 return Res;
837 }
838
839 // Otherwise, this must be a union that was converted to an integer value.
840 IntegerType *NTy = cast<IntegerType>(FromVal->getType());
841
842 // If this is a big-endian system and the load is narrower than the
843 // full alloca type, we need to do a shift to get the right bits.
844 int ShAmt = 0;
845 if (DL.isBigEndian()) {
846 // On big-endian machines, the lowest bit is stored at the bit offset
847 // from the pointer given by getTypeStoreSizeInBits. This matters for
848 // integers with a bitwidth that is not a multiple of 8.
849 ShAmt = DL.getTypeStoreSizeInBits(NTy) -
850 DL.getTypeStoreSizeInBits(ToType) - Offset;
851 } else {
852 ShAmt = Offset;
853 }
854
855 // Note: we support negative bitwidths (with shl) which are not defined.
856 // We do this to support (f.e.) loads off the end of a structure where
857 // only some bits are used.
858 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
859 FromVal = Builder.CreateLShr(FromVal,
860 ConstantInt::get(FromVal->getType(), ShAmt));
861 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
862 FromVal = Builder.CreateShl(FromVal,
863 ConstantInt::get(FromVal->getType(), -ShAmt));
864
865 // Finally, unconditionally truncate the integer to the right width.
866 unsigned LIBitWidth = DL.getTypeSizeInBits(ToType);
867 if (LIBitWidth < NTy->getBitWidth())
868 FromVal =
869 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
870 LIBitWidth));
871 else if (LIBitWidth > NTy->getBitWidth())
872 FromVal =
873 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
874 LIBitWidth));
875
876 // If the result is an integer, this is a trunc or bitcast.
877 if (ToType->isIntegerTy()) {
878 // Should be done.
879 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
880 // Just do a bitcast, we know the sizes match up.
881 FromVal = Builder.CreateBitCast(FromVal, ToType);
882 } else {
883 // Otherwise must be a pointer.
884 FromVal = Builder.CreateIntToPtr(FromVal, ToType);
885 }
886 assert(FromVal->getType() == ToType && "Didn't convert right?");
887 return FromVal;
888 }
889
890 /// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
891 /// or vector value "Old" at the offset specified by Offset.
892 ///
893 /// This happens when we are converting an "integer union" to a
894 /// single integer scalar, or when we are converting a "vector union" to a
895 /// vector with insert/extractelement instructions.
896 ///
897 /// Offset is an offset from the original alloca, in bits that need to be
898 /// shifted to the right.
899 ///
900 /// NonConstantIdx is an index value if there was a GEP with a non-constant
901 /// index value. If this is 0 then all GEPs used to find this insert address
902 /// are constant.
903 Value *ConvertToScalarInfo::
ConvertScalar_InsertValue(Value * SV,Value * Old,uint64_t Offset,Value * NonConstantIdx,IRBuilder<> & Builder)904 ConvertScalar_InsertValue(Value *SV, Value *Old,
905 uint64_t Offset, Value* NonConstantIdx,
906 IRBuilder<> &Builder) {
907 // Convert the stored type to the actual type, shift it left to insert
908 // then 'or' into place.
909 Type *AllocaType = Old->getType();
910 LLVMContext &Context = Old->getContext();
911
912 if (VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
913 uint64_t VecSize = DL.getTypeAllocSizeInBits(VTy);
914 uint64_t ValSize = DL.getTypeAllocSizeInBits(SV->getType());
915
916 // Changing the whole vector with memset or with an access of a different
917 // vector type?
918 if (ValSize == VecSize)
919 return Builder.CreateBitCast(SV, AllocaType);
920
921 // Must be an element insertion.
922 Type *EltTy = VTy->getElementType();
923 if (SV->getType() != EltTy)
924 SV = Builder.CreateBitCast(SV, EltTy);
925 uint64_t EltSize = DL.getTypeAllocSizeInBits(EltTy);
926 unsigned Elt = Offset/EltSize;
927 Value *Idx;
928 if (NonConstantIdx) {
929 if (Elt)
930 Idx = Builder.CreateAdd(NonConstantIdx,
931 Builder.getInt32(Elt),
932 "dyn.offset");
933 else
934 Idx = NonConstantIdx;
935 } else
936 Idx = Builder.getInt32(Elt);
937 return Builder.CreateInsertElement(Old, SV, Idx);
938 }
939
940 // If SV is a first-class aggregate value, insert each value recursively.
941 if (StructType *ST = dyn_cast<StructType>(SV->getType())) {
942 assert(!NonConstantIdx &&
943 "Dynamic indexing into struct types not supported");
944 const StructLayout &Layout = *DL.getStructLayout(ST);
945 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
946 Value *Elt = Builder.CreateExtractValue(SV, i);
947 Old = ConvertScalar_InsertValue(Elt, Old,
948 Offset+Layout.getElementOffsetInBits(i),
949 nullptr, Builder);
950 }
951 return Old;
952 }
953
954 if (ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
955 assert(!NonConstantIdx &&
956 "Dynamic indexing into array types not supported");
957 uint64_t EltSize = DL.getTypeAllocSizeInBits(AT->getElementType());
958 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
959 Value *Elt = Builder.CreateExtractValue(SV, i);
960 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, nullptr,
961 Builder);
962 }
963 return Old;
964 }
965
966 // If SV is a float, convert it to the appropriate integer type.
967 // If it is a pointer, do the same.
968 unsigned SrcWidth = DL.getTypeSizeInBits(SV->getType());
969 unsigned DestWidth = DL.getTypeSizeInBits(AllocaType);
970 unsigned SrcStoreWidth = DL.getTypeStoreSizeInBits(SV->getType());
971 unsigned DestStoreWidth = DL.getTypeStoreSizeInBits(AllocaType);
972 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
973 SV = Builder.CreateBitCast(SV, IntegerType::get(SV->getContext(),SrcWidth));
974 else if (SV->getType()->isPointerTy())
975 SV = Builder.CreatePtrToInt(SV, DL.getIntPtrType(SV->getType()));
976
977 // Zero extend or truncate the value if needed.
978 if (SV->getType() != AllocaType) {
979 if (SV->getType()->getPrimitiveSizeInBits() <
980 AllocaType->getPrimitiveSizeInBits())
981 SV = Builder.CreateZExt(SV, AllocaType);
982 else {
983 // Truncation may be needed if storing more than the alloca can hold
984 // (undefined behavior).
985 SV = Builder.CreateTrunc(SV, AllocaType);
986 SrcWidth = DestWidth;
987 SrcStoreWidth = DestStoreWidth;
988 }
989 }
990
991 // If this is a big-endian system and the store is narrower than the
992 // full alloca type, we need to do a shift to get the right bits.
993 int ShAmt = 0;
994 if (DL.isBigEndian()) {
995 // On big-endian machines, the lowest bit is stored at the bit offset
996 // from the pointer given by getTypeStoreSizeInBits. This matters for
997 // integers with a bitwidth that is not a multiple of 8.
998 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
999 } else {
1000 ShAmt = Offset;
1001 }
1002
1003 // Note: we support negative bitwidths (with shr) which are not defined.
1004 // We do this to support (f.e.) stores off the end of a structure where
1005 // only some bits in the structure are set.
1006 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1007 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1008 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(), ShAmt));
1009 Mask <<= ShAmt;
1010 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1011 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(), -ShAmt));
1012 Mask = Mask.lshr(-ShAmt);
1013 }
1014
1015 // Mask out the bits we are about to insert from the old value, and or
1016 // in the new bits.
1017 if (SrcWidth != DestWidth) {
1018 assert(DestWidth > SrcWidth);
1019 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
1020 SV = Builder.CreateOr(Old, SV, "ins");
1021 }
1022 return SV;
1023 }
1024
1025
1026 //===----------------------------------------------------------------------===//
1027 // SRoA Driver
1028 //===----------------------------------------------------------------------===//
1029
1030
runOnFunction(Function & F)1031 bool SROA::runOnFunction(Function &F) {
1032 if (skipOptnoneFunction(F))
1033 return false;
1034
1035 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1036 DL = DLP ? &DLP->getDataLayout() : nullptr;
1037
1038 bool Changed = performPromotion(F);
1039
1040 // FIXME: ScalarRepl currently depends on DataLayout more than it
1041 // theoretically needs to. It should be refactored in order to support
1042 // target-independent IR. Until this is done, just skip the actual
1043 // scalar-replacement portion of this pass.
1044 if (!DL) return Changed;
1045
1046 while (1) {
1047 bool LocalChange = performScalarRepl(F);
1048 if (!LocalChange) break; // No need to repromote if no scalarrepl
1049 Changed = true;
1050 LocalChange = performPromotion(F);
1051 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
1052 }
1053
1054 return Changed;
1055 }
1056
1057 namespace {
1058 class AllocaPromoter : public LoadAndStorePromoter {
1059 AllocaInst *AI;
1060 DIBuilder *DIB;
1061 SmallVector<DbgDeclareInst *, 4> DDIs;
1062 SmallVector<DbgValueInst *, 4> DVIs;
1063 public:
AllocaPromoter(const SmallVectorImpl<Instruction * > & Insts,SSAUpdater & S,DIBuilder * DB)1064 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1065 DIBuilder *DB)
1066 : LoadAndStorePromoter(Insts, S), AI(nullptr), DIB(DB) {}
1067
run(AllocaInst * AI,const SmallVectorImpl<Instruction * > & Insts)1068 void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
1069 // Remember which alloca we're promoting (for isInstInList).
1070 this->AI = AI;
1071 if (auto *L = LocalAsMetadata::getIfExists(AI)) {
1072 if (auto *DebugNode = MetadataAsValue::getIfExists(AI->getContext(), L)) {
1073 for (User *U : DebugNode->users())
1074 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
1075 DDIs.push_back(DDI);
1076 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
1077 DVIs.push_back(DVI);
1078 }
1079 }
1080
1081 LoadAndStorePromoter::run(Insts);
1082 AI->eraseFromParent();
1083 for (SmallVectorImpl<DbgDeclareInst *>::iterator I = DDIs.begin(),
1084 E = DDIs.end(); I != E; ++I) {
1085 DbgDeclareInst *DDI = *I;
1086 DDI->eraseFromParent();
1087 }
1088 for (SmallVectorImpl<DbgValueInst *>::iterator I = DVIs.begin(),
1089 E = DVIs.end(); I != E; ++I) {
1090 DbgValueInst *DVI = *I;
1091 DVI->eraseFromParent();
1092 }
1093 }
1094
isInstInList(Instruction * I,const SmallVectorImpl<Instruction * > & Insts) const1095 bool isInstInList(Instruction *I,
1096 const SmallVectorImpl<Instruction*> &Insts) const override {
1097 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1098 return LI->getOperand(0) == AI;
1099 return cast<StoreInst>(I)->getPointerOperand() == AI;
1100 }
1101
updateDebugInfo(Instruction * Inst) const1102 void updateDebugInfo(Instruction *Inst) const override {
1103 for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
1104 E = DDIs.end(); I != E; ++I) {
1105 DbgDeclareInst *DDI = *I;
1106 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1107 ConvertDebugDeclareToDebugValue(DDI, SI, *DIB);
1108 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1109 ConvertDebugDeclareToDebugValue(DDI, LI, *DIB);
1110 }
1111 for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
1112 E = DVIs.end(); I != E; ++I) {
1113 DbgValueInst *DVI = *I;
1114 Value *Arg = nullptr;
1115 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1116 // If an argument is zero extended then use argument directly. The ZExt
1117 // may be zapped by an optimization pass in future.
1118 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1119 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
1120 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1121 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1122 if (!Arg)
1123 Arg = SI->getOperand(0);
1124 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1125 Arg = LI->getOperand(0);
1126 } else {
1127 continue;
1128 }
1129 Instruction *DbgVal = DIB->insertDbgValueIntrinsic(
1130 Arg, 0, DIVariable(DVI->getVariable()),
1131 DIExpression(DVI->getExpression()), Inst);
1132 DbgVal->setDebugLoc(DVI->getDebugLoc());
1133 }
1134 }
1135 };
1136 } // end anon namespace
1137
1138 /// isSafeSelectToSpeculate - Select instructions that use an alloca and are
1139 /// subsequently loaded can be rewritten to load both input pointers and then
1140 /// select between the result, allowing the load of the alloca to be promoted.
1141 /// From this:
1142 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1143 /// %V = load i32* %P2
1144 /// to:
1145 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1146 /// %V2 = load i32* %Other
1147 /// %V = select i1 %cond, i32 %V1, i32 %V2
1148 ///
1149 /// We can do this to a select if its only uses are loads and if the operand to
1150 /// the select can be loaded unconditionally.
isSafeSelectToSpeculate(SelectInst * SI,const DataLayout * DL)1151 static bool isSafeSelectToSpeculate(SelectInst *SI, const DataLayout *DL) {
1152 bool TDerefable = SI->getTrueValue()->isDereferenceablePointer(DL);
1153 bool FDerefable = SI->getFalseValue()->isDereferenceablePointer(DL);
1154
1155 for (User *U : SI->users()) {
1156 LoadInst *LI = dyn_cast<LoadInst>(U);
1157 if (!LI || !LI->isSimple()) return false;
1158
1159 // Both operands to the select need to be dereferencable, either absolutely
1160 // (e.g. allocas) or at this point because we can see other accesses to it.
1161 if (!TDerefable && !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
1162 LI->getAlignment(), DL))
1163 return false;
1164 if (!FDerefable && !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
1165 LI->getAlignment(), DL))
1166 return false;
1167 }
1168
1169 return true;
1170 }
1171
1172 /// isSafePHIToSpeculate - PHI instructions that use an alloca and are
1173 /// subsequently loaded can be rewritten to load both input pointers in the pred
1174 /// blocks and then PHI the results, allowing the load of the alloca to be
1175 /// promoted.
1176 /// From this:
1177 /// %P2 = phi [i32* %Alloca, i32* %Other]
1178 /// %V = load i32* %P2
1179 /// to:
1180 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1181 /// ...
1182 /// %V2 = load i32* %Other
1183 /// ...
1184 /// %V = phi [i32 %V1, i32 %V2]
1185 ///
1186 /// We can do this to a select if its only uses are loads and if the operand to
1187 /// the select can be loaded unconditionally.
isSafePHIToSpeculate(PHINode * PN,const DataLayout * DL)1188 static bool isSafePHIToSpeculate(PHINode *PN, const DataLayout *DL) {
1189 // For now, we can only do this promotion if the load is in the same block as
1190 // the PHI, and if there are no stores between the phi and load.
1191 // TODO: Allow recursive phi users.
1192 // TODO: Allow stores.
1193 BasicBlock *BB = PN->getParent();
1194 unsigned MaxAlign = 0;
1195 for (User *U : PN->users()) {
1196 LoadInst *LI = dyn_cast<LoadInst>(U);
1197 if (!LI || !LI->isSimple()) return false;
1198
1199 // For now we only allow loads in the same block as the PHI. This is a
1200 // common case that happens when instcombine merges two loads through a PHI.
1201 if (LI->getParent() != BB) return false;
1202
1203 // Ensure that there are no instructions between the PHI and the load that
1204 // could store.
1205 for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
1206 if (BBI->mayWriteToMemory())
1207 return false;
1208
1209 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1210 }
1211
1212 // Okay, we know that we have one or more loads in the same block as the PHI.
1213 // We can transform this if it is safe to push the loads into the predecessor
1214 // blocks. The only thing to watch out for is that we can't put a possibly
1215 // trapping load in the predecessor if it is a critical edge.
1216 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1217 BasicBlock *Pred = PN->getIncomingBlock(i);
1218 Value *InVal = PN->getIncomingValue(i);
1219
1220 // If the terminator of the predecessor has side-effects (an invoke),
1221 // there is no safe place to put a load in the predecessor.
1222 if (Pred->getTerminator()->mayHaveSideEffects())
1223 return false;
1224
1225 // If the value is produced by the terminator of the predecessor
1226 // (an invoke), there is no valid place to put a load in the predecessor.
1227 if (Pred->getTerminator() == InVal)
1228 return false;
1229
1230 // If the predecessor has a single successor, then the edge isn't critical.
1231 if (Pred->getTerminator()->getNumSuccessors() == 1)
1232 continue;
1233
1234 // If this pointer is always safe to load, or if we can prove that there is
1235 // already a load in the block, then we can move the load to the pred block.
1236 if (InVal->isDereferenceablePointer(DL) ||
1237 isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign, DL))
1238 continue;
1239
1240 return false;
1241 }
1242
1243 return true;
1244 }
1245
1246
1247 /// tryToMakeAllocaBePromotable - This returns true if the alloca only has
1248 /// direct (non-volatile) loads and stores to it. If the alloca is close but
1249 /// not quite there, this will transform the code to allow promotion. As such,
1250 /// it is a non-pure predicate.
tryToMakeAllocaBePromotable(AllocaInst * AI,const DataLayout * DL)1251 static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const DataLayout *DL) {
1252 SetVector<Instruction*, SmallVector<Instruction*, 4>,
1253 SmallPtrSet<Instruction*, 4> > InstsToRewrite;
1254 for (User *U : AI->users()) {
1255 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1256 if (!LI->isSimple())
1257 return false;
1258 continue;
1259 }
1260
1261 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1262 if (SI->getOperand(0) == AI || !SI->isSimple())
1263 return false; // Don't allow a store OF the AI, only INTO the AI.
1264 continue;
1265 }
1266
1267 if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
1268 // If the condition being selected on is a constant, fold the select, yes
1269 // this does (rarely) happen early on.
1270 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
1271 Value *Result = SI->getOperand(1+CI->isZero());
1272 SI->replaceAllUsesWith(Result);
1273 SI->eraseFromParent();
1274
1275 // This is very rare and we just scrambled the use list of AI, start
1276 // over completely.
1277 return tryToMakeAllocaBePromotable(AI, DL);
1278 }
1279
1280 // If it is safe to turn "load (select c, AI, ptr)" into a select of two
1281 // loads, then we can transform this by rewriting the select.
1282 if (!isSafeSelectToSpeculate(SI, DL))
1283 return false;
1284
1285 InstsToRewrite.insert(SI);
1286 continue;
1287 }
1288
1289 if (PHINode *PN = dyn_cast<PHINode>(U)) {
1290 if (PN->use_empty()) { // Dead PHIs can be stripped.
1291 InstsToRewrite.insert(PN);
1292 continue;
1293 }
1294
1295 // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
1296 // in the pred blocks, then we can transform this by rewriting the PHI.
1297 if (!isSafePHIToSpeculate(PN, DL))
1298 return false;
1299
1300 InstsToRewrite.insert(PN);
1301 continue;
1302 }
1303
1304 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
1305 if (onlyUsedByLifetimeMarkers(BCI)) {
1306 InstsToRewrite.insert(BCI);
1307 continue;
1308 }
1309 }
1310
1311 return false;
1312 }
1313
1314 // If there are no instructions to rewrite, then all uses are load/stores and
1315 // we're done!
1316 if (InstsToRewrite.empty())
1317 return true;
1318
1319 // If we have instructions that need to be rewritten for this to be promotable
1320 // take care of it now.
1321 for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
1322 if (BitCastInst *BCI = dyn_cast<BitCastInst>(InstsToRewrite[i])) {
1323 // This could only be a bitcast used by nothing but lifetime intrinsics.
1324 for (BitCastInst::user_iterator I = BCI->user_begin(), E = BCI->user_end();
1325 I != E;)
1326 cast<Instruction>(*I++)->eraseFromParent();
1327 BCI->eraseFromParent();
1328 continue;
1329 }
1330
1331 if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
1332 // Selects in InstsToRewrite only have load uses. Rewrite each as two
1333 // loads with a new select.
1334 while (!SI->use_empty()) {
1335 LoadInst *LI = cast<LoadInst>(SI->user_back());
1336
1337 IRBuilder<> Builder(LI);
1338 LoadInst *TrueLoad =
1339 Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t");
1340 LoadInst *FalseLoad =
1341 Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".f");
1342
1343 // Transfer alignment and AA info if present.
1344 TrueLoad->setAlignment(LI->getAlignment());
1345 FalseLoad->setAlignment(LI->getAlignment());
1346
1347 AAMDNodes Tags;
1348 LI->getAAMetadata(Tags);
1349 if (Tags) {
1350 TrueLoad->setAAMetadata(Tags);
1351 FalseLoad->setAAMetadata(Tags);
1352 }
1353
1354 Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
1355 V->takeName(LI);
1356 LI->replaceAllUsesWith(V);
1357 LI->eraseFromParent();
1358 }
1359
1360 // Now that all the loads are gone, the select is gone too.
1361 SI->eraseFromParent();
1362 continue;
1363 }
1364
1365 // Otherwise, we have a PHI node which allows us to push the loads into the
1366 // predecessors.
1367 PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
1368 if (PN->use_empty()) {
1369 PN->eraseFromParent();
1370 continue;
1371 }
1372
1373 Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
1374 PHINode *NewPN = PHINode::Create(LoadTy, PN->getNumIncomingValues(),
1375 PN->getName()+".ld", PN);
1376
1377 // Get the AA tags and alignment to use from one of the loads. It doesn't
1378 // matter which one we get and if any differ, it doesn't matter.
1379 LoadInst *SomeLoad = cast<LoadInst>(PN->user_back());
1380
1381 AAMDNodes AATags;
1382 SomeLoad->getAAMetadata(AATags);
1383 unsigned Align = SomeLoad->getAlignment();
1384
1385 // Rewrite all loads of the PN to use the new PHI.
1386 while (!PN->use_empty()) {
1387 LoadInst *LI = cast<LoadInst>(PN->user_back());
1388 LI->replaceAllUsesWith(NewPN);
1389 LI->eraseFromParent();
1390 }
1391
1392 // Inject loads into all of the pred blocks. Keep track of which blocks we
1393 // insert them into in case we have multiple edges from the same block.
1394 DenseMap<BasicBlock*, LoadInst*> InsertedLoads;
1395
1396 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1397 BasicBlock *Pred = PN->getIncomingBlock(i);
1398 LoadInst *&Load = InsertedLoads[Pred];
1399 if (!Load) {
1400 Load = new LoadInst(PN->getIncomingValue(i),
1401 PN->getName() + "." + Pred->getName(),
1402 Pred->getTerminator());
1403 Load->setAlignment(Align);
1404 if (AATags) Load->setAAMetadata(AATags);
1405 }
1406
1407 NewPN->addIncoming(Load, Pred);
1408 }
1409
1410 PN->eraseFromParent();
1411 }
1412
1413 ++NumAdjusted;
1414 return true;
1415 }
1416
performPromotion(Function & F)1417 bool SROA::performPromotion(Function &F) {
1418 std::vector<AllocaInst*> Allocas;
1419 DominatorTree *DT = nullptr;
1420 if (HasDomTree)
1421 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1422 AssumptionCache &AC =
1423 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1424
1425 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
1426 DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
1427 bool Changed = false;
1428 SmallVector<Instruction*, 64> Insts;
1429 while (1) {
1430 Allocas.clear();
1431
1432 // Find allocas that are safe to promote, by looking at all instructions in
1433 // the entry node
1434 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
1435 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
1436 if (tryToMakeAllocaBePromotable(AI, DL))
1437 Allocas.push_back(AI);
1438
1439 if (Allocas.empty()) break;
1440
1441 if (HasDomTree)
1442 PromoteMemToReg(Allocas, *DT, nullptr, &AC);
1443 else {
1444 SSAUpdater SSA;
1445 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
1446 AllocaInst *AI = Allocas[i];
1447
1448 // Build list of instructions to promote.
1449 for (User *U : AI->users())
1450 Insts.push_back(cast<Instruction>(U));
1451 AllocaPromoter(Insts, SSA, &DIB).run(AI, Insts);
1452 Insts.clear();
1453 }
1454 }
1455 NumPromoted += Allocas.size();
1456 Changed = true;
1457 }
1458
1459 return Changed;
1460 }
1461
1462
1463 /// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
1464 /// SROA. It must be a struct or array type with a small number of elements.
ShouldAttemptScalarRepl(AllocaInst * AI)1465 bool SROA::ShouldAttemptScalarRepl(AllocaInst *AI) {
1466 Type *T = AI->getAllocatedType();
1467 // Do not promote any struct that has too many members.
1468 if (StructType *ST = dyn_cast<StructType>(T))
1469 return ST->getNumElements() <= StructMemberThreshold;
1470 // Do not promote any array that has too many elements.
1471 if (ArrayType *AT = dyn_cast<ArrayType>(T))
1472 return AT->getNumElements() <= ArrayElementThreshold;
1473 return false;
1474 }
1475
1476 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
1477 // which runs on all of the alloca instructions in the entry block, removing
1478 // them if they are only used by getelementptr instructions.
1479 //
performScalarRepl(Function & F)1480 bool SROA::performScalarRepl(Function &F) {
1481 std::vector<AllocaInst*> WorkList;
1482
1483 // Scan the entry basic block, adding allocas to the worklist.
1484 BasicBlock &BB = F.getEntryBlock();
1485 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
1486 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
1487 WorkList.push_back(A);
1488
1489 // Process the worklist
1490 bool Changed = false;
1491 while (!WorkList.empty()) {
1492 AllocaInst *AI = WorkList.back();
1493 WorkList.pop_back();
1494
1495 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
1496 // with unused elements.
1497 if (AI->use_empty()) {
1498 AI->eraseFromParent();
1499 Changed = true;
1500 continue;
1501 }
1502
1503 // If this alloca is impossible for us to promote, reject it early.
1504 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
1505 continue;
1506
1507 // Check to see if we can perform the core SROA transformation. We cannot
1508 // transform the allocation instruction if it is an array allocation
1509 // (allocations OF arrays are ok though), and an allocation of a scalar
1510 // value cannot be decomposed at all.
1511 uint64_t AllocaSize = DL->getTypeAllocSize(AI->getAllocatedType());
1512
1513 // Do not promote [0 x %struct].
1514 if (AllocaSize == 0) continue;
1515
1516 // Do not promote any struct whose size is too big.
1517 if (AllocaSize > SRThreshold) continue;
1518
1519 // If the alloca looks like a good candidate for scalar replacement, and if
1520 // all its users can be transformed, then split up the aggregate into its
1521 // separate elements.
1522 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
1523 DoScalarReplacement(AI, WorkList);
1524 Changed = true;
1525 continue;
1526 }
1527
1528 // If we can turn this aggregate value (potentially with casts) into a
1529 // simple scalar value that can be mem2reg'd into a register value.
1530 // IsNotTrivial tracks whether this is something that mem2reg could have
1531 // promoted itself. If so, we don't want to transform it needlessly. Note
1532 // that we can't just check based on the type: the alloca may be of an i32
1533 // but that has pointer arithmetic to set byte 3 of it or something.
1534 if (AllocaInst *NewAI = ConvertToScalarInfo(
1535 (unsigned)AllocaSize, *DL, ScalarLoadThreshold).TryConvert(AI)) {
1536 NewAI->takeName(AI);
1537 AI->eraseFromParent();
1538 ++NumConverted;
1539 Changed = true;
1540 continue;
1541 }
1542
1543 // Otherwise, couldn't process this alloca.
1544 }
1545
1546 return Changed;
1547 }
1548
1549 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1550 /// predicate, do SROA now.
DoScalarReplacement(AllocaInst * AI,std::vector<AllocaInst * > & WorkList)1551 void SROA::DoScalarReplacement(AllocaInst *AI,
1552 std::vector<AllocaInst*> &WorkList) {
1553 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
1554 SmallVector<AllocaInst*, 32> ElementAllocas;
1555 if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1556 ElementAllocas.reserve(ST->getNumContainedTypes());
1557 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
1558 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), nullptr,
1559 AI->getAlignment(),
1560 AI->getName() + "." + Twine(i), AI);
1561 ElementAllocas.push_back(NA);
1562 WorkList.push_back(NA); // Add to worklist for recursive processing
1563 }
1564 } else {
1565 ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
1566 ElementAllocas.reserve(AT->getNumElements());
1567 Type *ElTy = AT->getElementType();
1568 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1569 AllocaInst *NA = new AllocaInst(ElTy, nullptr, AI->getAlignment(),
1570 AI->getName() + "." + Twine(i), AI);
1571 ElementAllocas.push_back(NA);
1572 WorkList.push_back(NA); // Add to worklist for recursive processing
1573 }
1574 }
1575
1576 // Now that we have created the new alloca instructions, rewrite all the
1577 // uses of the old alloca.
1578 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
1579
1580 // Now erase any instructions that were made dead while rewriting the alloca.
1581 DeleteDeadInstructions();
1582 AI->eraseFromParent();
1583
1584 ++NumReplaced;
1585 }
1586
1587 /// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1588 /// recursively including all their operands that become trivially dead.
DeleteDeadInstructions()1589 void SROA::DeleteDeadInstructions() {
1590 while (!DeadInsts.empty()) {
1591 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
1592
1593 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1594 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1595 // Zero out the operand and see if it becomes trivially dead.
1596 // (But, don't add allocas to the dead instruction list -- they are
1597 // already on the worklist and will be deleted separately.)
1598 *OI = nullptr;
1599 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1600 DeadInsts.push_back(U);
1601 }
1602
1603 I->eraseFromParent();
1604 }
1605 }
1606
1607 /// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1608 /// performing scalar replacement of alloca AI. The results are flagged in
1609 /// the Info parameter. Offset indicates the position within AI that is
1610 /// referenced by this instruction.
isSafeForScalarRepl(Instruction * I,uint64_t Offset,AllocaInfo & Info)1611 void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
1612 AllocaInfo &Info) {
1613 for (Use &U : I->uses()) {
1614 Instruction *User = cast<Instruction>(U.getUser());
1615
1616 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1617 isSafeForScalarRepl(BC, Offset, Info);
1618 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1619 uint64_t GEPOffset = Offset;
1620 isSafeGEP(GEPI, GEPOffset, Info);
1621 if (!Info.isUnsafe)
1622 isSafeForScalarRepl(GEPI, GEPOffset, Info);
1623 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1624 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1625 if (!Length || Length->isNegative())
1626 return MarkUnsafe(Info, User);
1627
1628 isSafeMemAccess(Offset, Length->getZExtValue(), nullptr,
1629 U.getOperandNo() == 0, Info, MI,
1630 true /*AllowWholeAccess*/);
1631 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1632 if (!LI->isSimple())
1633 return MarkUnsafe(Info, User);
1634 Type *LIType = LI->getType();
1635 isSafeMemAccess(Offset, DL->getTypeAllocSize(LIType),
1636 LIType, false, Info, LI, true /*AllowWholeAccess*/);
1637 Info.hasALoadOrStore = true;
1638
1639 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1640 // Store is ok if storing INTO the pointer, not storing the pointer
1641 if (!SI->isSimple() || SI->getOperand(0) == I)
1642 return MarkUnsafe(Info, User);
1643
1644 Type *SIType = SI->getOperand(0)->getType();
1645 isSafeMemAccess(Offset, DL->getTypeAllocSize(SIType),
1646 SIType, true, Info, SI, true /*AllowWholeAccess*/);
1647 Info.hasALoadOrStore = true;
1648 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
1649 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1650 II->getIntrinsicID() != Intrinsic::lifetime_end)
1651 return MarkUnsafe(Info, User);
1652 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1653 isSafePHISelectUseForScalarRepl(User, Offset, Info);
1654 } else {
1655 return MarkUnsafe(Info, User);
1656 }
1657 if (Info.isUnsafe) return;
1658 }
1659 }
1660
1661
1662 /// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
1663 /// derived from the alloca, we can often still split the alloca into elements.
1664 /// This is useful if we have a large alloca where one element is phi'd
1665 /// together somewhere: we can SRoA and promote all the other elements even if
1666 /// we end up not being able to promote this one.
1667 ///
1668 /// All we require is that the uses of the PHI do not index into other parts of
1669 /// the alloca. The most important use case for this is single load and stores
1670 /// that are PHI'd together, which can happen due to code sinking.
isSafePHISelectUseForScalarRepl(Instruction * I,uint64_t Offset,AllocaInfo & Info)1671 void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
1672 AllocaInfo &Info) {
1673 // If we've already checked this PHI, don't do it again.
1674 if (PHINode *PN = dyn_cast<PHINode>(I))
1675 if (!Info.CheckedPHIs.insert(PN).second)
1676 return;
1677
1678 for (User *U : I->users()) {
1679 Instruction *UI = cast<Instruction>(U);
1680
1681 if (BitCastInst *BC = dyn_cast<BitCastInst>(UI)) {
1682 isSafePHISelectUseForScalarRepl(BC, Offset, Info);
1683 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(UI)) {
1684 // Only allow "bitcast" GEPs for simplicity. We could generalize this,
1685 // but would have to prove that we're staying inside of an element being
1686 // promoted.
1687 if (!GEPI->hasAllZeroIndices())
1688 return MarkUnsafe(Info, UI);
1689 isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
1690 } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
1691 if (!LI->isSimple())
1692 return MarkUnsafe(Info, UI);
1693 Type *LIType = LI->getType();
1694 isSafeMemAccess(Offset, DL->getTypeAllocSize(LIType),
1695 LIType, false, Info, LI, false /*AllowWholeAccess*/);
1696 Info.hasALoadOrStore = true;
1697
1698 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1699 // Store is ok if storing INTO the pointer, not storing the pointer
1700 if (!SI->isSimple() || SI->getOperand(0) == I)
1701 return MarkUnsafe(Info, UI);
1702
1703 Type *SIType = SI->getOperand(0)->getType();
1704 isSafeMemAccess(Offset, DL->getTypeAllocSize(SIType),
1705 SIType, true, Info, SI, false /*AllowWholeAccess*/);
1706 Info.hasALoadOrStore = true;
1707 } else if (isa<PHINode>(UI) || isa<SelectInst>(UI)) {
1708 isSafePHISelectUseForScalarRepl(UI, Offset, Info);
1709 } else {
1710 return MarkUnsafe(Info, UI);
1711 }
1712 if (Info.isUnsafe) return;
1713 }
1714 }
1715
1716 /// isSafeGEP - Check if a GEP instruction can be handled for scalar
1717 /// replacement. It is safe when all the indices are constant, in-bounds
1718 /// references, and when the resulting offset corresponds to an element within
1719 /// the alloca type. The results are flagged in the Info parameter. Upon
1720 /// return, Offset is adjusted as specified by the GEP indices.
isSafeGEP(GetElementPtrInst * GEPI,uint64_t & Offset,AllocaInfo & Info)1721 void SROA::isSafeGEP(GetElementPtrInst *GEPI,
1722 uint64_t &Offset, AllocaInfo &Info) {
1723 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1724 if (GEPIt == E)
1725 return;
1726 bool NonConstant = false;
1727 unsigned NonConstantIdxSize = 0;
1728
1729 // Walk through the GEP type indices, checking the types that this indexes
1730 // into.
1731 for (; GEPIt != E; ++GEPIt) {
1732 // Ignore struct elements, no extra checking needed for these.
1733 if ((*GEPIt)->isStructTy())
1734 continue;
1735
1736 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1737 if (!IdxVal)
1738 return MarkUnsafe(Info, GEPI);
1739 }
1740
1741 // Compute the offset due to this GEP and check if the alloca has a
1742 // component element at that offset.
1743 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1744 // If this GEP is non-constant then the last operand must have been a
1745 // dynamic index into a vector. Pop this now as it has no impact on the
1746 // constant part of the offset.
1747 if (NonConstant)
1748 Indices.pop_back();
1749 Offset += DL->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
1750 if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset,
1751 NonConstantIdxSize))
1752 MarkUnsafe(Info, GEPI);
1753 }
1754
1755 /// isHomogeneousAggregate - Check if type T is a struct or array containing
1756 /// elements of the same type (which is always true for arrays). If so,
1757 /// return true with NumElts and EltTy set to the number of elements and the
1758 /// element type, respectively.
isHomogeneousAggregate(Type * T,unsigned & NumElts,Type * & EltTy)1759 static bool isHomogeneousAggregate(Type *T, unsigned &NumElts,
1760 Type *&EltTy) {
1761 if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
1762 NumElts = AT->getNumElements();
1763 EltTy = (NumElts == 0 ? nullptr : AT->getElementType());
1764 return true;
1765 }
1766 if (StructType *ST = dyn_cast<StructType>(T)) {
1767 NumElts = ST->getNumContainedTypes();
1768 EltTy = (NumElts == 0 ? nullptr : ST->getContainedType(0));
1769 for (unsigned n = 1; n < NumElts; ++n) {
1770 if (ST->getContainedType(n) != EltTy)
1771 return false;
1772 }
1773 return true;
1774 }
1775 return false;
1776 }
1777
1778 /// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1779 /// "homogeneous" aggregates with the same element type and number of elements.
isCompatibleAggregate(Type * T1,Type * T2)1780 static bool isCompatibleAggregate(Type *T1, Type *T2) {
1781 if (T1 == T2)
1782 return true;
1783
1784 unsigned NumElts1, NumElts2;
1785 Type *EltTy1, *EltTy2;
1786 if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1787 isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1788 NumElts1 == NumElts2 &&
1789 EltTy1 == EltTy2)
1790 return true;
1791
1792 return false;
1793 }
1794
1795 /// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1796 /// alloca or has an offset and size that corresponds to a component element
1797 /// within it. The offset checked here may have been formed from a GEP with a
1798 /// pointer bitcasted to a different type.
1799 ///
1800 /// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
1801 /// unit. If false, it only allows accesses known to be in a single element.
isSafeMemAccess(uint64_t Offset,uint64_t MemSize,Type * MemOpType,bool isStore,AllocaInfo & Info,Instruction * TheAccess,bool AllowWholeAccess)1802 void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
1803 Type *MemOpType, bool isStore,
1804 AllocaInfo &Info, Instruction *TheAccess,
1805 bool AllowWholeAccess) {
1806 // Check if this is a load/store of the entire alloca.
1807 if (Offset == 0 && AllowWholeAccess &&
1808 MemSize == DL->getTypeAllocSize(Info.AI->getAllocatedType())) {
1809 // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1810 // loads/stores (which are essentially the same as the MemIntrinsics with
1811 // regard to copying padding between elements). But, if an alloca is
1812 // flagged as both a source and destination of such operations, we'll need
1813 // to check later for padding between elements.
1814 if (!MemOpType || MemOpType->isIntegerTy()) {
1815 if (isStore)
1816 Info.isMemCpyDst = true;
1817 else
1818 Info.isMemCpySrc = true;
1819 return;
1820 }
1821 // This is also safe for references using a type that is compatible with
1822 // the type of the alloca, so that loads/stores can be rewritten using
1823 // insertvalue/extractvalue.
1824 if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
1825 Info.hasSubelementAccess = true;
1826 return;
1827 }
1828 }
1829 // Check if the offset/size correspond to a component within the alloca type.
1830 Type *T = Info.AI->getAllocatedType();
1831 if (TypeHasComponent(T, Offset, MemSize)) {
1832 Info.hasSubelementAccess = true;
1833 return;
1834 }
1835
1836 return MarkUnsafe(Info, TheAccess);
1837 }
1838
1839 /// TypeHasComponent - Return true if T has a component type with the
1840 /// specified offset and size. If Size is zero, do not check the size.
TypeHasComponent(Type * T,uint64_t Offset,uint64_t Size)1841 bool SROA::TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size) {
1842 Type *EltTy;
1843 uint64_t EltSize;
1844 if (StructType *ST = dyn_cast<StructType>(T)) {
1845 const StructLayout *Layout = DL->getStructLayout(ST);
1846 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1847 EltTy = ST->getContainedType(EltIdx);
1848 EltSize = DL->getTypeAllocSize(EltTy);
1849 Offset -= Layout->getElementOffset(EltIdx);
1850 } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
1851 EltTy = AT->getElementType();
1852 EltSize = DL->getTypeAllocSize(EltTy);
1853 if (Offset >= AT->getNumElements() * EltSize)
1854 return false;
1855 Offset %= EltSize;
1856 } else if (VectorType *VT = dyn_cast<VectorType>(T)) {
1857 EltTy = VT->getElementType();
1858 EltSize = DL->getTypeAllocSize(EltTy);
1859 if (Offset >= VT->getNumElements() * EltSize)
1860 return false;
1861 Offset %= EltSize;
1862 } else {
1863 return false;
1864 }
1865 if (Offset == 0 && (Size == 0 || EltSize == Size))
1866 return true;
1867 // Check if the component spans multiple elements.
1868 if (Offset + Size > EltSize)
1869 return false;
1870 return TypeHasComponent(EltTy, Offset, Size);
1871 }
1872
1873 /// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1874 /// the instruction I, which references it, to use the separate elements.
1875 /// Offset indicates the position within AI that is referenced by this
1876 /// instruction.
RewriteForScalarRepl(Instruction * I,AllocaInst * AI,uint64_t Offset,SmallVectorImpl<AllocaInst * > & NewElts)1877 void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1878 SmallVectorImpl<AllocaInst *> &NewElts) {
1879 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
1880 Use &TheUse = *UI++;
1881 Instruction *User = cast<Instruction>(TheUse.getUser());
1882
1883 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1884 RewriteBitCast(BC, AI, Offset, NewElts);
1885 continue;
1886 }
1887
1888 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1889 RewriteGEP(GEPI, AI, Offset, NewElts);
1890 continue;
1891 }
1892
1893 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1894 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1895 uint64_t MemSize = Length->getZExtValue();
1896 if (Offset == 0 &&
1897 MemSize == DL->getTypeAllocSize(AI->getAllocatedType()))
1898 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
1899 // Otherwise the intrinsic can only touch a single element and the
1900 // address operand will be updated, so nothing else needs to be done.
1901 continue;
1902 }
1903
1904 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
1905 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
1906 II->getIntrinsicID() == Intrinsic::lifetime_end) {
1907 RewriteLifetimeIntrinsic(II, AI, Offset, NewElts);
1908 }
1909 continue;
1910 }
1911
1912 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1913 Type *LIType = LI->getType();
1914
1915 if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
1916 // Replace:
1917 // %res = load { i32, i32 }* %alloc
1918 // with:
1919 // %load.0 = load i32* %alloc.0
1920 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1921 // %load.1 = load i32* %alloc.1
1922 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1923 // (Also works for arrays instead of structs)
1924 Value *Insert = UndefValue::get(LIType);
1925 IRBuilder<> Builder(LI);
1926 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1927 Value *Load = Builder.CreateLoad(NewElts[i], "load");
1928 Insert = Builder.CreateInsertValue(Insert, Load, i, "insert");
1929 }
1930 LI->replaceAllUsesWith(Insert);
1931 DeadInsts.push_back(LI);
1932 } else if (LIType->isIntegerTy() &&
1933 DL->getTypeAllocSize(LIType) ==
1934 DL->getTypeAllocSize(AI->getAllocatedType())) {
1935 // If this is a load of the entire alloca to an integer, rewrite it.
1936 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1937 }
1938 continue;
1939 }
1940
1941 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1942 Value *Val = SI->getOperand(0);
1943 Type *SIType = Val->getType();
1944 if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
1945 // Replace:
1946 // store { i32, i32 } %val, { i32, i32 }* %alloc
1947 // with:
1948 // %val.0 = extractvalue { i32, i32 } %val, 0
1949 // store i32 %val.0, i32* %alloc.0
1950 // %val.1 = extractvalue { i32, i32 } %val, 1
1951 // store i32 %val.1, i32* %alloc.1
1952 // (Also works for arrays instead of structs)
1953 IRBuilder<> Builder(SI);
1954 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1955 Value *Extract = Builder.CreateExtractValue(Val, i, Val->getName());
1956 Builder.CreateStore(Extract, NewElts[i]);
1957 }
1958 DeadInsts.push_back(SI);
1959 } else if (SIType->isIntegerTy() &&
1960 DL->getTypeAllocSize(SIType) ==
1961 DL->getTypeAllocSize(AI->getAllocatedType())) {
1962 // If this is a store of the entire alloca from an integer, rewrite it.
1963 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1964 }
1965 continue;
1966 }
1967
1968 if (isa<SelectInst>(User) || isa<PHINode>(User)) {
1969 // If we have a PHI user of the alloca itself (as opposed to a GEP or
1970 // bitcast) we have to rewrite it. GEP and bitcast uses will be RAUW'd to
1971 // the new pointer.
1972 if (!isa<AllocaInst>(I)) continue;
1973
1974 assert(Offset == 0 && NewElts[0] &&
1975 "Direct alloca use should have a zero offset");
1976
1977 // If we have a use of the alloca, we know the derived uses will be
1978 // utilizing just the first element of the scalarized result. Insert a
1979 // bitcast of the first alloca before the user as required.
1980 AllocaInst *NewAI = NewElts[0];
1981 BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
1982 NewAI->moveBefore(BCI);
1983 TheUse = BCI;
1984 continue;
1985 }
1986 }
1987 }
1988
1989 /// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1990 /// and recursively continue updating all of its uses.
RewriteBitCast(BitCastInst * BC,AllocaInst * AI,uint64_t Offset,SmallVectorImpl<AllocaInst * > & NewElts)1991 void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1992 SmallVectorImpl<AllocaInst *> &NewElts) {
1993 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1994 if (BC->getOperand(0) != AI)
1995 return;
1996
1997 // The bitcast references the original alloca. Replace its uses with
1998 // references to the alloca containing offset zero (which is normally at
1999 // index zero, but might not be in cases involving structs with elements
2000 // of size zero).
2001 Type *T = AI->getAllocatedType();
2002 uint64_t EltOffset = 0;
2003 Type *IdxTy;
2004 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
2005 Instruction *Val = NewElts[Idx];
2006 if (Val->getType() != BC->getDestTy()) {
2007 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
2008 Val->takeName(BC);
2009 }
2010 BC->replaceAllUsesWith(Val);
2011 DeadInsts.push_back(BC);
2012 }
2013
2014 /// FindElementAndOffset - Return the index of the element containing Offset
2015 /// within the specified type, which must be either a struct or an array.
2016 /// Sets T to the type of the element and Offset to the offset within that
2017 /// element. IdxTy is set to the type of the index result to be used in a
2018 /// GEP instruction.
FindElementAndOffset(Type * & T,uint64_t & Offset,Type * & IdxTy)2019 uint64_t SROA::FindElementAndOffset(Type *&T, uint64_t &Offset,
2020 Type *&IdxTy) {
2021 uint64_t Idx = 0;
2022 if (StructType *ST = dyn_cast<StructType>(T)) {
2023 const StructLayout *Layout = DL->getStructLayout(ST);
2024 Idx = Layout->getElementContainingOffset(Offset);
2025 T = ST->getContainedType(Idx);
2026 Offset -= Layout->getElementOffset(Idx);
2027 IdxTy = Type::getInt32Ty(T->getContext());
2028 return Idx;
2029 } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
2030 T = AT->getElementType();
2031 uint64_t EltSize = DL->getTypeAllocSize(T);
2032 Idx = Offset / EltSize;
2033 Offset -= Idx * EltSize;
2034 IdxTy = Type::getInt64Ty(T->getContext());
2035 return Idx;
2036 }
2037 VectorType *VT = cast<VectorType>(T);
2038 T = VT->getElementType();
2039 uint64_t EltSize = DL->getTypeAllocSize(T);
2040 Idx = Offset / EltSize;
2041 Offset -= Idx * EltSize;
2042 IdxTy = Type::getInt64Ty(T->getContext());
2043 return Idx;
2044 }
2045
2046 /// RewriteGEP - Check if this GEP instruction moves the pointer across
2047 /// elements of the alloca that are being split apart, and if so, rewrite
2048 /// the GEP to be relative to the new element.
RewriteGEP(GetElementPtrInst * GEPI,AllocaInst * AI,uint64_t Offset,SmallVectorImpl<AllocaInst * > & NewElts)2049 void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
2050 SmallVectorImpl<AllocaInst *> &NewElts) {
2051 uint64_t OldOffset = Offset;
2052 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
2053 // If the GEP was dynamic then it must have been a dynamic vector lookup.
2054 // In this case, it must be the last GEP operand which is dynamic so keep that
2055 // aside until we've found the constant GEP offset then add it back in at the
2056 // end.
2057 Value* NonConstantIdx = nullptr;
2058 if (!GEPI->hasAllConstantIndices())
2059 NonConstantIdx = Indices.pop_back_val();
2060 Offset += DL->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
2061
2062 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
2063
2064 Type *T = AI->getAllocatedType();
2065 Type *IdxTy;
2066 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
2067 if (GEPI->getOperand(0) == AI)
2068 OldIdx = ~0ULL; // Force the GEP to be rewritten.
2069
2070 T = AI->getAllocatedType();
2071 uint64_t EltOffset = Offset;
2072 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
2073
2074 // If this GEP does not move the pointer across elements of the alloca
2075 // being split, then it does not needs to be rewritten.
2076 if (Idx == OldIdx)
2077 return;
2078
2079 Type *i32Ty = Type::getInt32Ty(AI->getContext());
2080 SmallVector<Value*, 8> NewArgs;
2081 NewArgs.push_back(Constant::getNullValue(i32Ty));
2082 while (EltOffset != 0) {
2083 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
2084 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
2085 }
2086 if (NonConstantIdx) {
2087 Type* GepTy = T;
2088 // This GEP has a dynamic index. We need to add "i32 0" to index through
2089 // any structs or arrays in the original type until we get to the vector
2090 // to index.
2091 while (!isa<VectorType>(GepTy)) {
2092 NewArgs.push_back(Constant::getNullValue(i32Ty));
2093 GepTy = cast<CompositeType>(GepTy)->getTypeAtIndex(0U);
2094 }
2095 NewArgs.push_back(NonConstantIdx);
2096 }
2097 Instruction *Val = NewElts[Idx];
2098 if (NewArgs.size() > 1) {
2099 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs, "", GEPI);
2100 Val->takeName(GEPI);
2101 }
2102 if (Val->getType() != GEPI->getType())
2103 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
2104 GEPI->replaceAllUsesWith(Val);
2105 DeadInsts.push_back(GEPI);
2106 }
2107
2108 /// RewriteLifetimeIntrinsic - II is a lifetime.start/lifetime.end. Rewrite it
2109 /// to mark the lifetime of the scalarized memory.
RewriteLifetimeIntrinsic(IntrinsicInst * II,AllocaInst * AI,uint64_t Offset,SmallVectorImpl<AllocaInst * > & NewElts)2110 void SROA::RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
2111 uint64_t Offset,
2112 SmallVectorImpl<AllocaInst *> &NewElts) {
2113 ConstantInt *OldSize = cast<ConstantInt>(II->getArgOperand(0));
2114 // Put matching lifetime markers on everything from Offset up to
2115 // Offset+OldSize.
2116 Type *AIType = AI->getAllocatedType();
2117 uint64_t NewOffset = Offset;
2118 Type *IdxTy;
2119 uint64_t Idx = FindElementAndOffset(AIType, NewOffset, IdxTy);
2120
2121 IRBuilder<> Builder(II);
2122 uint64_t Size = OldSize->getLimitedValue();
2123
2124 if (NewOffset) {
2125 // Splice the first element and index 'NewOffset' bytes in. SROA will
2126 // split the alloca again later.
2127 unsigned AS = AI->getType()->getAddressSpace();
2128 Value *V = Builder.CreateBitCast(NewElts[Idx], Builder.getInt8PtrTy(AS));
2129 V = Builder.CreateGEP(V, Builder.getInt64(NewOffset));
2130
2131 IdxTy = NewElts[Idx]->getAllocatedType();
2132 uint64_t EltSize = DL->getTypeAllocSize(IdxTy) - NewOffset;
2133 if (EltSize > Size) {
2134 EltSize = Size;
2135 Size = 0;
2136 } else {
2137 Size -= EltSize;
2138 }
2139 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
2140 Builder.CreateLifetimeStart(V, Builder.getInt64(EltSize));
2141 else
2142 Builder.CreateLifetimeEnd(V, Builder.getInt64(EltSize));
2143 ++Idx;
2144 }
2145
2146 for (; Idx != NewElts.size() && Size; ++Idx) {
2147 IdxTy = NewElts[Idx]->getAllocatedType();
2148 uint64_t EltSize = DL->getTypeAllocSize(IdxTy);
2149 if (EltSize > Size) {
2150 EltSize = Size;
2151 Size = 0;
2152 } else {
2153 Size -= EltSize;
2154 }
2155 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
2156 Builder.CreateLifetimeStart(NewElts[Idx],
2157 Builder.getInt64(EltSize));
2158 else
2159 Builder.CreateLifetimeEnd(NewElts[Idx],
2160 Builder.getInt64(EltSize));
2161 }
2162 DeadInsts.push_back(II);
2163 }
2164
2165 /// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
2166 /// Rewrite it to copy or set the elements of the scalarized memory.
2167 void
RewriteMemIntrinUserOfAlloca(MemIntrinsic * MI,Instruction * Inst,AllocaInst * AI,SmallVectorImpl<AllocaInst * > & NewElts)2168 SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
2169 AllocaInst *AI,
2170 SmallVectorImpl<AllocaInst *> &NewElts) {
2171 // If this is a memcpy/memmove, construct the other pointer as the
2172 // appropriate type. The "Other" pointer is the pointer that goes to memory
2173 // that doesn't have anything to do with the alloca that we are promoting. For
2174 // memset, this Value* stays null.
2175 Value *OtherPtr = nullptr;
2176 unsigned MemAlignment = MI->getAlignment();
2177 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
2178 if (Inst == MTI->getRawDest())
2179 OtherPtr = MTI->getRawSource();
2180 else {
2181 assert(Inst == MTI->getRawSource());
2182 OtherPtr = MTI->getRawDest();
2183 }
2184 }
2185
2186 // If there is an other pointer, we want to convert it to the same pointer
2187 // type as AI has, so we can GEP through it safely.
2188 if (OtherPtr) {
2189 unsigned AddrSpace =
2190 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
2191
2192 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
2193 // optimization, but it's also required to detect the corner case where
2194 // both pointer operands are referencing the same memory, and where
2195 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
2196 // function is only called for mem intrinsics that access the whole
2197 // aggregate, so non-zero GEPs are not an issue here.)
2198 OtherPtr = OtherPtr->stripPointerCasts();
2199
2200 // Copying the alloca to itself is a no-op: just delete it.
2201 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
2202 // This code will run twice for a no-op memcpy -- once for each operand.
2203 // Put only one reference to MI on the DeadInsts list.
2204 for (SmallVectorImpl<Value *>::const_iterator I = DeadInsts.begin(),
2205 E = DeadInsts.end(); I != E; ++I)
2206 if (*I == MI) return;
2207 DeadInsts.push_back(MI);
2208 return;
2209 }
2210
2211 // If the pointer is not the right type, insert a bitcast to the right
2212 // type.
2213 Type *NewTy =
2214 PointerType::get(AI->getType()->getElementType(), AddrSpace);
2215
2216 if (OtherPtr->getType() != NewTy)
2217 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
2218 }
2219
2220 // Process each element of the aggregate.
2221 bool SROADest = MI->getRawDest() == Inst;
2222
2223 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
2224
2225 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2226 // If this is a memcpy/memmove, emit a GEP of the other element address.
2227 Value *OtherElt = nullptr;
2228 unsigned OtherEltAlign = MemAlignment;
2229
2230 if (OtherPtr) {
2231 Value *Idx[2] = { Zero,
2232 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
2233 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx,
2234 OtherPtr->getName()+"."+Twine(i),
2235 MI);
2236 uint64_t EltOffset;
2237 PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
2238 Type *OtherTy = OtherPtrTy->getElementType();
2239 if (StructType *ST = dyn_cast<StructType>(OtherTy)) {
2240 EltOffset = DL->getStructLayout(ST)->getElementOffset(i);
2241 } else {
2242 Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
2243 EltOffset = DL->getTypeAllocSize(EltTy)*i;
2244 }
2245
2246 // The alignment of the other pointer is the guaranteed alignment of the
2247 // element, which is affected by both the known alignment of the whole
2248 // mem intrinsic and the alignment of the element. If the alignment of
2249 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
2250 // known alignment is just 4 bytes.
2251 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
2252 }
2253
2254 Value *EltPtr = NewElts[i];
2255 Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
2256
2257 // If we got down to a scalar, insert a load or store as appropriate.
2258 if (EltTy->isSingleValueType()) {
2259 if (isa<MemTransferInst>(MI)) {
2260 if (SROADest) {
2261 // From Other to Alloca.
2262 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
2263 new StoreInst(Elt, EltPtr, MI);
2264 } else {
2265 // From Alloca to Other.
2266 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
2267 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
2268 }
2269 continue;
2270 }
2271 assert(isa<MemSetInst>(MI));
2272
2273 // If the stored element is zero (common case), just store a null
2274 // constant.
2275 Constant *StoreVal;
2276 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
2277 if (CI->isZero()) {
2278 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
2279 } else {
2280 // If EltTy is a vector type, get the element type.
2281 Type *ValTy = EltTy->getScalarType();
2282
2283 // Construct an integer with the right value.
2284 unsigned EltSize = DL->getTypeSizeInBits(ValTy);
2285 APInt OneVal(EltSize, CI->getZExtValue());
2286 APInt TotalVal(OneVal);
2287 // Set each byte.
2288 for (unsigned i = 0; 8*i < EltSize; ++i) {
2289 TotalVal = TotalVal.shl(8);
2290 TotalVal |= OneVal;
2291 }
2292
2293 // Convert the integer value to the appropriate type.
2294 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
2295 if (ValTy->isPointerTy())
2296 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
2297 else if (ValTy->isFloatingPointTy())
2298 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
2299 assert(StoreVal->getType() == ValTy && "Type mismatch!");
2300
2301 // If the requested value was a vector constant, create it.
2302 if (EltTy->isVectorTy()) {
2303 unsigned NumElts = cast<VectorType>(EltTy)->getNumElements();
2304 StoreVal = ConstantVector::getSplat(NumElts, StoreVal);
2305 }
2306 }
2307 new StoreInst(StoreVal, EltPtr, MI);
2308 continue;
2309 }
2310 // Otherwise, if we're storing a byte variable, use a memset call for
2311 // this element.
2312 }
2313
2314 unsigned EltSize = DL->getTypeAllocSize(EltTy);
2315 if (!EltSize)
2316 continue;
2317
2318 IRBuilder<> Builder(MI);
2319
2320 // Finally, insert the meminst for this element.
2321 if (isa<MemSetInst>(MI)) {
2322 Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
2323 MI->isVolatile());
2324 } else {
2325 assert(isa<MemTransferInst>(MI));
2326 Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr
2327 Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr
2328
2329 if (isa<MemCpyInst>(MI))
2330 Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
2331 else
2332 Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
2333 }
2334 }
2335 DeadInsts.push_back(MI);
2336 }
2337
2338 /// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
2339 /// overwrites the entire allocation. Extract out the pieces of the stored
2340 /// integer and store them individually.
2341 void
RewriteStoreUserOfWholeAlloca(StoreInst * SI,AllocaInst * AI,SmallVectorImpl<AllocaInst * > & NewElts)2342 SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
2343 SmallVectorImpl<AllocaInst *> &NewElts) {
2344 // Extract each element out of the integer according to its structure offset
2345 // and store the element value to the individual alloca.
2346 Value *SrcVal = SI->getOperand(0);
2347 Type *AllocaEltTy = AI->getAllocatedType();
2348 uint64_t AllocaSizeBits = DL->getTypeAllocSizeInBits(AllocaEltTy);
2349
2350 IRBuilder<> Builder(SI);
2351
2352 // Handle tail padding by extending the operand
2353 if (DL->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
2354 SrcVal = Builder.CreateZExt(SrcVal,
2355 IntegerType::get(SI->getContext(), AllocaSizeBits));
2356
2357 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
2358 << '\n');
2359
2360 // There are two forms here: AI could be an array or struct. Both cases
2361 // have different ways to compute the element offset.
2362 if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2363 const StructLayout *Layout = DL->getStructLayout(EltSTy);
2364
2365 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2366 // Get the number of bits to shift SrcVal to get the value.
2367 Type *FieldTy = EltSTy->getElementType(i);
2368 uint64_t Shift = Layout->getElementOffsetInBits(i);
2369
2370 if (DL->isBigEndian())
2371 Shift = AllocaSizeBits-Shift-DL->getTypeAllocSizeInBits(FieldTy);
2372
2373 Value *EltVal = SrcVal;
2374 if (Shift) {
2375 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
2376 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
2377 }
2378
2379 // Truncate down to an integer of the right size.
2380 uint64_t FieldSizeBits = DL->getTypeSizeInBits(FieldTy);
2381
2382 // Ignore zero sized fields like {}, they obviously contain no data.
2383 if (FieldSizeBits == 0) continue;
2384
2385 if (FieldSizeBits != AllocaSizeBits)
2386 EltVal = Builder.CreateTrunc(EltVal,
2387 IntegerType::get(SI->getContext(), FieldSizeBits));
2388 Value *DestField = NewElts[i];
2389 if (EltVal->getType() == FieldTy) {
2390 // Storing to an integer field of this size, just do it.
2391 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
2392 // Bitcast to the right element type (for fp/vector values).
2393 EltVal = Builder.CreateBitCast(EltVal, FieldTy);
2394 } else {
2395 // Otherwise, bitcast the dest pointer (for aggregates).
2396 DestField = Builder.CreateBitCast(DestField,
2397 PointerType::getUnqual(EltVal->getType()));
2398 }
2399 new StoreInst(EltVal, DestField, SI);
2400 }
2401
2402 } else {
2403 ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
2404 Type *ArrayEltTy = ATy->getElementType();
2405 uint64_t ElementOffset = DL->getTypeAllocSizeInBits(ArrayEltTy);
2406 uint64_t ElementSizeBits = DL->getTypeSizeInBits(ArrayEltTy);
2407
2408 uint64_t Shift;
2409
2410 if (DL->isBigEndian())
2411 Shift = AllocaSizeBits-ElementOffset;
2412 else
2413 Shift = 0;
2414
2415 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2416 // Ignore zero sized fields like {}, they obviously contain no data.
2417 if (ElementSizeBits == 0) continue;
2418
2419 Value *EltVal = SrcVal;
2420 if (Shift) {
2421 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
2422 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
2423 }
2424
2425 // Truncate down to an integer of the right size.
2426 if (ElementSizeBits != AllocaSizeBits)
2427 EltVal = Builder.CreateTrunc(EltVal,
2428 IntegerType::get(SI->getContext(),
2429 ElementSizeBits));
2430 Value *DestField = NewElts[i];
2431 if (EltVal->getType() == ArrayEltTy) {
2432 // Storing to an integer field of this size, just do it.
2433 } else if (ArrayEltTy->isFloatingPointTy() ||
2434 ArrayEltTy->isVectorTy()) {
2435 // Bitcast to the right element type (for fp/vector values).
2436 EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
2437 } else {
2438 // Otherwise, bitcast the dest pointer (for aggregates).
2439 DestField = Builder.CreateBitCast(DestField,
2440 PointerType::getUnqual(EltVal->getType()));
2441 }
2442 new StoreInst(EltVal, DestField, SI);
2443
2444 if (DL->isBigEndian())
2445 Shift -= ElementOffset;
2446 else
2447 Shift += ElementOffset;
2448 }
2449 }
2450
2451 DeadInsts.push_back(SI);
2452 }
2453
2454 /// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
2455 /// an integer. Load the individual pieces to form the aggregate value.
2456 void
RewriteLoadUserOfWholeAlloca(LoadInst * LI,AllocaInst * AI,SmallVectorImpl<AllocaInst * > & NewElts)2457 SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
2458 SmallVectorImpl<AllocaInst *> &NewElts) {
2459 // Extract each element out of the NewElts according to its structure offset
2460 // and form the result value.
2461 Type *AllocaEltTy = AI->getAllocatedType();
2462 uint64_t AllocaSizeBits = DL->getTypeAllocSizeInBits(AllocaEltTy);
2463
2464 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
2465 << '\n');
2466
2467 // There are two forms here: AI could be an array or struct. Both cases
2468 // have different ways to compute the element offset.
2469 const StructLayout *Layout = nullptr;
2470 uint64_t ArrayEltBitOffset = 0;
2471 if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2472 Layout = DL->getStructLayout(EltSTy);
2473 } else {
2474 Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
2475 ArrayEltBitOffset = DL->getTypeAllocSizeInBits(ArrayEltTy);
2476 }
2477
2478 Value *ResultVal =
2479 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
2480
2481 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2482 // Load the value from the alloca. If the NewElt is an aggregate, cast
2483 // the pointer to an integer of the same size before doing the load.
2484 Value *SrcField = NewElts[i];
2485 Type *FieldTy =
2486 cast<PointerType>(SrcField->getType())->getElementType();
2487 uint64_t FieldSizeBits = DL->getTypeSizeInBits(FieldTy);
2488
2489 // Ignore zero sized fields like {}, they obviously contain no data.
2490 if (FieldSizeBits == 0) continue;
2491
2492 IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
2493 FieldSizeBits);
2494 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
2495 !FieldTy->isVectorTy())
2496 SrcField = new BitCastInst(SrcField,
2497 PointerType::getUnqual(FieldIntTy),
2498 "", LI);
2499 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
2500
2501 // If SrcField is a fp or vector of the right size but that isn't an
2502 // integer type, bitcast to an integer so we can shift it.
2503 if (SrcField->getType() != FieldIntTy)
2504 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
2505
2506 // Zero extend the field to be the same size as the final alloca so that
2507 // we can shift and insert it.
2508 if (SrcField->getType() != ResultVal->getType())
2509 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
2510
2511 // Determine the number of bits to shift SrcField.
2512 uint64_t Shift;
2513 if (Layout) // Struct case.
2514 Shift = Layout->getElementOffsetInBits(i);
2515 else // Array case.
2516 Shift = i*ArrayEltBitOffset;
2517
2518 if (DL->isBigEndian())
2519 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
2520
2521 if (Shift) {
2522 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
2523 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
2524 }
2525
2526 // Don't create an 'or x, 0' on the first iteration.
2527 if (!isa<Constant>(ResultVal) ||
2528 !cast<Constant>(ResultVal)->isNullValue())
2529 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
2530 else
2531 ResultVal = SrcField;
2532 }
2533
2534 // Handle tail padding by truncating the result
2535 if (DL->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
2536 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
2537
2538 LI->replaceAllUsesWith(ResultVal);
2539 DeadInsts.push_back(LI);
2540 }
2541
2542 /// HasPadding - Return true if the specified type has any structure or
2543 /// alignment padding in between the elements that would be split apart
2544 /// by SROA; return false otherwise.
HasPadding(Type * Ty,const DataLayout & DL)2545 static bool HasPadding(Type *Ty, const DataLayout &DL) {
2546 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2547 Ty = ATy->getElementType();
2548 return DL.getTypeSizeInBits(Ty) != DL.getTypeAllocSizeInBits(Ty);
2549 }
2550
2551 // SROA currently handles only Arrays and Structs.
2552 StructType *STy = cast<StructType>(Ty);
2553 const StructLayout *SL = DL.getStructLayout(STy);
2554 unsigned PrevFieldBitOffset = 0;
2555 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2556 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
2557
2558 // Check to see if there is any padding between this element and the
2559 // previous one.
2560 if (i) {
2561 unsigned PrevFieldEnd =
2562 PrevFieldBitOffset+DL.getTypeSizeInBits(STy->getElementType(i-1));
2563 if (PrevFieldEnd < FieldBitOffset)
2564 return true;
2565 }
2566 PrevFieldBitOffset = FieldBitOffset;
2567 }
2568 // Check for tail padding.
2569 if (unsigned EltCount = STy->getNumElements()) {
2570 unsigned PrevFieldEnd = PrevFieldBitOffset +
2571 DL.getTypeSizeInBits(STy->getElementType(EltCount-1));
2572 if (PrevFieldEnd < SL->getSizeInBits())
2573 return true;
2574 }
2575 return false;
2576 }
2577
2578 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
2579 /// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
2580 /// or 1 if safe after canonicalization has been performed.
isSafeAllocaToScalarRepl(AllocaInst * AI)2581 bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
2582 // Loop over the use list of the alloca. We can only transform it if all of
2583 // the users are safe to transform.
2584 AllocaInfo Info(AI);
2585
2586 isSafeForScalarRepl(AI, 0, Info);
2587 if (Info.isUnsafe) {
2588 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
2589 return false;
2590 }
2591
2592 // Okay, we know all the users are promotable. If the aggregate is a memcpy
2593 // source and destination, we have to be careful. In particular, the memcpy
2594 // could be moving around elements that live in structure padding of the LLVM
2595 // types, but may actually be used. In these cases, we refuse to promote the
2596 // struct.
2597 if (Info.isMemCpySrc && Info.isMemCpyDst &&
2598 HasPadding(AI->getAllocatedType(), *DL))
2599 return false;
2600
2601 // If the alloca never has an access to just *part* of it, but is accessed
2602 // via loads and stores, then we should use ConvertToScalarInfo to promote
2603 // the alloca instead of promoting each piece at a time and inserting fission
2604 // and fusion code.
2605 if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
2606 // If the struct/array just has one element, use basic SRoA.
2607 if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
2608 if (ST->getNumElements() > 1) return false;
2609 } else {
2610 if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
2611 return false;
2612 }
2613 }
2614
2615 return true;
2616 }
2617