ScalarReplAggregates.cpp revision 963a97f1a365c8d09ca681e922371f9ec3473ee8
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
17// often interact, especially for C++ programs.  As such, iterating between
18// SRoA, then Mem2Reg until we run out of things to promote works well.
19//
20//===----------------------------------------------------------------------===//
21
22#define DEBUG_TYPE "scalarrepl"
23#include "llvm/Transforms/Scalar.h"
24#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
26#include "llvm/Function.h"
27#include "llvm/GlobalVariable.h"
28#include "llvm/Instructions.h"
29#include "llvm/IntrinsicInst.h"
30#include "llvm/Pass.h"
31#include "llvm/Analysis/Dominators.h"
32#include "llvm/Target/TargetData.h"
33#include "llvm/Transforms/Utils/PromoteMemToReg.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/Support/GetElementPtrTypeIterator.h"
36#include "llvm/Support/MathExtras.h"
37#include "llvm/Support/Compiler.h"
38#include "llvm/ADT/SmallVector.h"
39#include "llvm/ADT/Statistic.h"
40#include "llvm/ADT/StringExtras.h"
41using namespace llvm;
42
43STATISTIC(NumReplaced,  "Number of allocas broken up");
44STATISTIC(NumPromoted,  "Number of allocas promoted");
45STATISTIC(NumConverted, "Number of aggregates converted to scalar");
46STATISTIC(NumGlobals,   "Number of allocas copied from constant global");
47
48namespace {
49  struct VISIBILITY_HIDDEN SROA : public FunctionPass {
50    static char ID; // Pass identification, replacement for typeid
51    explicit SROA(signed T = -1) : FunctionPass((intptr_t)&ID) {
52      if (T == -1)
53        SRThreshold = 128;
54      else
55        SRThreshold = T;
56    }
57
58    bool runOnFunction(Function &F);
59
60    bool performScalarRepl(Function &F);
61    bool performPromotion(Function &F);
62
63    // getAnalysisUsage - This pass does not require any passes, but we know it
64    // will not alter the CFG, so say so.
65    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
66      AU.addRequired<DominatorTree>();
67      AU.addRequired<DominanceFrontier>();
68      AU.addRequired<TargetData>();
69      AU.setPreservesCFG();
70    }
71
72  private:
73    /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
74    /// information about the uses.  All these fields are initialized to false
75    /// and set to true when something is learned.
76    struct AllocaInfo {
77      /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
78      bool isUnsafe : 1;
79
80      /// needsCanon - This is set to true if there is some use of the alloca
81      /// that requires canonicalization.
82      bool needsCanon : 1;
83
84      /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
85      bool isMemCpySrc : 1;
86
87      /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
88      bool isMemCpyDst : 1;
89
90      AllocaInfo()
91        : isUnsafe(false), needsCanon(false),
92          isMemCpySrc(false), isMemCpyDst(false) {}
93    };
94
95    unsigned SRThreshold;
96
97    void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
98
99    int isSafeAllocaToScalarRepl(AllocationInst *AI);
100
101    void isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
102                               AllocaInfo &Info);
103    void isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
104                         AllocaInfo &Info);
105    void isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
106                                        unsigned OpNo, AllocaInfo &Info);
107    void isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI,
108                                        AllocaInfo &Info);
109
110    void DoScalarReplacement(AllocationInst *AI,
111                             std::vector<AllocationInst*> &WorkList);
112    void CanonicalizeAllocaUsers(AllocationInst *AI);
113    AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
114
115    void RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
116                                    SmallVector<AllocaInst*, 32> &NewElts);
117
118    const Type *CanConvertToScalar(Value *V, bool &IsNotTrivial);
119    void ConvertToScalar(AllocationInst *AI, const Type *Ty);
120    void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset);
121    Value *ConvertUsesOfLoadToScalar(LoadInst *LI, AllocaInst *NewAI,
122                                     unsigned Offset);
123    Value *ConvertUsesOfStoreToScalar(StoreInst *SI, AllocaInst *NewAI,
124                                      unsigned Offset);
125    static Instruction *isOnlyCopiedFromConstantGlobal(AllocationInst *AI);
126  };
127}
128
129char SROA::ID = 0;
130static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
131
132// Public interface to the ScalarReplAggregates pass
133FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
134  return new SROA(Threshold);
135}
136
137
138bool SROA::runOnFunction(Function &F) {
139  bool Changed = performPromotion(F);
140  while (1) {
141    bool LocalChange = performScalarRepl(F);
142    if (!LocalChange) break;   // No need to repromote if no scalarrepl
143    Changed = true;
144    LocalChange = performPromotion(F);
145    if (!LocalChange) break;   // No need to re-scalarrepl if no promotion
146  }
147
148  return Changed;
149}
150
151
152bool SROA::performPromotion(Function &F) {
153  std::vector<AllocaInst*> Allocas;
154  DominatorTree         &DT = getAnalysis<DominatorTree>();
155  DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
156
157  BasicBlock &BB = F.getEntryBlock();  // Get the entry node for the function
158
159  bool Changed = false;
160
161  while (1) {
162    Allocas.clear();
163
164    // Find allocas that are safe to promote, by looking at all instructions in
165    // the entry node
166    for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
167      if (AllocaInst *AI = dyn_cast<AllocaInst>(I))       // Is it an alloca?
168        if (isAllocaPromotable(AI))
169          Allocas.push_back(AI);
170
171    if (Allocas.empty()) break;
172
173    PromoteMemToReg(Allocas, DT, DF);
174    NumPromoted += Allocas.size();
175    Changed = true;
176  }
177
178  return Changed;
179}
180
181/// getNumSAElements - Return the number of elements in the specific struct or
182/// array.
183static uint64_t getNumSAElements(const Type *T) {
184  if (const StructType *ST = dyn_cast<StructType>(T))
185    return ST->getNumElements();
186  return cast<ArrayType>(T)->getNumElements();
187}
188
189// performScalarRepl - This algorithm is a simple worklist driven algorithm,
190// which runs on all of the malloc/alloca instructions in the function, removing
191// them if they are only used by getelementptr instructions.
192//
193bool SROA::performScalarRepl(Function &F) {
194  std::vector<AllocationInst*> WorkList;
195
196  // Scan the entry basic block, adding any alloca's and mallocs to the worklist
197  BasicBlock &BB = F.getEntryBlock();
198  for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
199    if (AllocationInst *A = dyn_cast<AllocationInst>(I))
200      WorkList.push_back(A);
201
202  const TargetData &TD = getAnalysis<TargetData>();
203
204  // Process the worklist
205  bool Changed = false;
206  while (!WorkList.empty()) {
207    AllocationInst *AI = WorkList.back();
208    WorkList.pop_back();
209
210    // Handle dead allocas trivially.  These can be formed by SROA'ing arrays
211    // with unused elements.
212    if (AI->use_empty()) {
213      AI->eraseFromParent();
214      continue;
215    }
216
217    // If we can turn this aggregate value (potentially with casts) into a
218    // simple scalar value that can be mem2reg'd into a register value.
219    bool IsNotTrivial = false;
220    if (const Type *ActualType = CanConvertToScalar(AI, IsNotTrivial))
221      if (IsNotTrivial && ActualType != Type::VoidTy) {
222        ConvertToScalar(AI, ActualType);
223        Changed = true;
224        continue;
225      }
226
227    // Check to see if we can perform the core SROA transformation.  We cannot
228    // transform the allocation instruction if it is an array allocation
229    // (allocations OF arrays are ok though), and an allocation of a scalar
230    // value cannot be decomposed at all.
231    if (!AI->isArrayAllocation() &&
232        (isa<StructType>(AI->getAllocatedType()) ||
233         isa<ArrayType>(AI->getAllocatedType())) &&
234        AI->getAllocatedType()->isSized() &&
235        // Do not promote any struct whose size is larger than "128" bytes.
236        TD.getABITypeSize(AI->getAllocatedType()) < SRThreshold &&
237        // Do not promote any struct into more than "32" separate vars.
238        getNumSAElements(AI->getAllocatedType()) < SRThreshold/4) {
239      // Check that all of the users of the allocation are capable of being
240      // transformed.
241      switch (isSafeAllocaToScalarRepl(AI)) {
242      default: assert(0 && "Unexpected value!");
243      case 0:  // Not safe to scalar replace.
244        break;
245      case 1:  // Safe, but requires cleanup/canonicalizations first
246        CanonicalizeAllocaUsers(AI);
247        // FALL THROUGH.
248      case 3:  // Safe to scalar replace.
249        DoScalarReplacement(AI, WorkList);
250        Changed = true;
251        continue;
252      }
253    }
254
255    // Check to see if this allocation is only modified by a memcpy/memmove from
256    // a constant global.  If this is the case, we can change all users to use
257    // the constant global instead.  This is commonly produced by the CFE by
258    // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
259    // is only subsequently read.
260    if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
261      DOUT << "Found alloca equal to global: " << *AI;
262      DOUT << "  memcpy = " << *TheCopy;
263      Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
264      AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
265      TheCopy->eraseFromParent();  // Don't mutate the global.
266      AI->eraseFromParent();
267      ++NumGlobals;
268      Changed = true;
269      continue;
270    }
271
272    // Otherwise, couldn't process this.
273  }
274
275  return Changed;
276}
277
278/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
279/// predicate, do SROA now.
280void SROA::DoScalarReplacement(AllocationInst *AI,
281                               std::vector<AllocationInst*> &WorkList) {
282  DOUT << "Found inst to SROA: " << *AI;
283  SmallVector<AllocaInst*, 32> ElementAllocas;
284  if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
285    ElementAllocas.reserve(ST->getNumContainedTypes());
286    for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
287      AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
288                                      AI->getAlignment(),
289                                      AI->getName() + "." + utostr(i), AI);
290      ElementAllocas.push_back(NA);
291      WorkList.push_back(NA);  // Add to worklist for recursive processing
292    }
293  } else {
294    const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
295    ElementAllocas.reserve(AT->getNumElements());
296    const Type *ElTy = AT->getElementType();
297    for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
298      AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
299                                      AI->getName() + "." + utostr(i), AI);
300      ElementAllocas.push_back(NA);
301      WorkList.push_back(NA);  // Add to worklist for recursive processing
302    }
303  }
304
305  // Now that we have created the alloca instructions that we want to use,
306  // expand the getelementptr instructions to use them.
307  //
308  while (!AI->use_empty()) {
309    Instruction *User = cast<Instruction>(AI->use_back());
310    if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
311      RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
312      BCInst->eraseFromParent();
313      continue;
314    }
315
316    // Replace %res = load { i32, i32 }* %alloc
317    // by
318    // %load.0 = load i32* %alloc.0
319    // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
320    // %load.1 = load i32* %alloc.1
321    // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
322    // (Also works for arrays instead of structs)
323    if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
324      Value *Insert = UndefValue::get(LI->getType());
325      for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
326        Value *Load = new LoadInst(ElementAllocas[i], "load", LI);
327        Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
328      }
329      LI->replaceAllUsesWith(Insert);
330      LI->eraseFromParent();
331      continue;
332    }
333
334    // Replace store { i32, i32 } %val, { i32, i32 }* %alloc
335    // by
336    // %val.0 = extractvalue { i32, i32 } %val, 0
337    // store i32 %val.0, i32* %alloc.0
338    // %val.1 = extractvalue { i32, i32 } %val, 1
339    // store i32 %val.1, i32* %alloc.1
340    // (Also works for arrays instead of structs)
341    if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
342      Value *Val = SI->getOperand(0);
343      for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
344        Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
345        new StoreInst(Extract, ElementAllocas[i], SI);
346      }
347      SI->eraseFromParent();
348      continue;
349    }
350
351    GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
352    // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
353    unsigned Idx =
354       (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
355
356    assert(Idx < ElementAllocas.size() && "Index out of range?");
357    AllocaInst *AllocaToUse = ElementAllocas[Idx];
358
359    Value *RepValue;
360    if (GEPI->getNumOperands() == 3) {
361      // Do not insert a new getelementptr instruction with zero indices, only
362      // to have it optimized out later.
363      RepValue = AllocaToUse;
364    } else {
365      // We are indexing deeply into the structure, so we still need a
366      // getelement ptr instruction to finish the indexing.  This may be
367      // expanded itself once the worklist is rerun.
368      //
369      SmallVector<Value*, 8> NewArgs;
370      NewArgs.push_back(Constant::getNullValue(Type::Int32Ty));
371      NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
372      RepValue = GetElementPtrInst::Create(AllocaToUse, NewArgs.begin(),
373                                           NewArgs.end(), "", GEPI);
374      RepValue->takeName(GEPI);
375    }
376
377    // If this GEP is to the start of the aggregate, check for memcpys.
378    if (Idx == 0) {
379      bool IsStartOfAggregateGEP = true;
380      for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i) {
381        if (!isa<ConstantInt>(GEPI->getOperand(i))) {
382          IsStartOfAggregateGEP = false;
383          break;
384        }
385        if (!cast<ConstantInt>(GEPI->getOperand(i))->isZero()) {
386          IsStartOfAggregateGEP = false;
387          break;
388        }
389      }
390
391      if (IsStartOfAggregateGEP)
392        RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas);
393    }
394
395
396    // Move all of the users over to the new GEP.
397    GEPI->replaceAllUsesWith(RepValue);
398    // Delete the old GEP
399    GEPI->eraseFromParent();
400  }
401
402  // Finally, delete the Alloca instruction
403  AI->eraseFromParent();
404  NumReplaced++;
405}
406
407
408/// isSafeElementUse - Check to see if this use is an allowed use for a
409/// getelementptr instruction of an array aggregate allocation.  isFirstElt
410/// indicates whether Ptr is known to the start of the aggregate.
411///
412void SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
413                            AllocaInfo &Info) {
414  for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
415       I != E; ++I) {
416    Instruction *User = cast<Instruction>(*I);
417    switch (User->getOpcode()) {
418    case Instruction::Load:  break;
419    case Instruction::Store:
420      // Store is ok if storing INTO the pointer, not storing the pointer
421      if (User->getOperand(0) == Ptr) return MarkUnsafe(Info);
422      break;
423    case Instruction::GetElementPtr: {
424      GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
425      bool AreAllZeroIndices = isFirstElt;
426      if (GEP->getNumOperands() > 1) {
427        if (!isa<ConstantInt>(GEP->getOperand(1)) ||
428            !cast<ConstantInt>(GEP->getOperand(1))->isZero())
429          // Using pointer arithmetic to navigate the array.
430          return MarkUnsafe(Info);
431
432        if (AreAllZeroIndices) {
433          for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) {
434            if (!isa<ConstantInt>(GEP->getOperand(i)) ||
435                !cast<ConstantInt>(GEP->getOperand(i))->isZero()) {
436              AreAllZeroIndices = false;
437              break;
438            }
439          }
440        }
441      }
442      isSafeElementUse(GEP, AreAllZeroIndices, AI, Info);
443      if (Info.isUnsafe) return;
444      break;
445    }
446    case Instruction::BitCast:
447      if (isFirstElt) {
448        isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI, Info);
449        if (Info.isUnsafe) return;
450        break;
451      }
452      DOUT << "  Transformation preventing inst: " << *User;
453      return MarkUnsafe(Info);
454    case Instruction::Call:
455      if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
456        if (isFirstElt) {
457          isSafeMemIntrinsicOnAllocation(MI, AI, I.getOperandNo(), Info);
458          if (Info.isUnsafe) return;
459          break;
460        }
461      }
462      DOUT << "  Transformation preventing inst: " << *User;
463      return MarkUnsafe(Info);
464    default:
465      DOUT << "  Transformation preventing inst: " << *User;
466      return MarkUnsafe(Info);
467    }
468  }
469  return;  // All users look ok :)
470}
471
472/// AllUsersAreLoads - Return true if all users of this value are loads.
473static bool AllUsersAreLoads(Value *Ptr) {
474  for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
475       I != E; ++I)
476    if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
477      return false;
478  return true;
479}
480
481/// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
482/// aggregate allocation.
483///
484void SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
485                                 AllocaInfo &Info) {
486  if (BitCastInst *C = dyn_cast<BitCastInst>(User))
487    return isSafeUseOfBitCastedAllocation(C, AI, Info);
488
489  if (isa<LoadInst>(User))
490    return; // Loads (returning a first class aggregrate) are always rewritable
491
492  if (isa<StoreInst>(User) && User->getOperand(0) != AI)
493    return; // Store is ok if storing INTO the pointer, not storing the pointer
494
495  GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User);
496  if (GEPI == 0)
497    return MarkUnsafe(Info);
498
499  gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
500
501  // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
502  if (I == E ||
503      I.getOperand() != Constant::getNullValue(I.getOperand()->getType())) {
504    return MarkUnsafe(Info);
505  }
506
507  ++I;
508  if (I == E) return MarkUnsafe(Info);  // ran out of GEP indices??
509
510  bool IsAllZeroIndices = true;
511
512  // If this is a use of an array allocation, do a bit more checking for sanity.
513  if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
514    uint64_t NumElements = AT->getNumElements();
515
516    if (ConstantInt *Idx = dyn_cast<ConstantInt>(I.getOperand())) {
517      IsAllZeroIndices &= Idx->isZero();
518
519      // Check to make sure that index falls within the array.  If not,
520      // something funny is going on, so we won't do the optimization.
521      //
522      if (Idx->getZExtValue() >= NumElements)
523        return MarkUnsafe(Info);
524
525      // We cannot scalar repl this level of the array unless any array
526      // sub-indices are in-range constants.  In particular, consider:
527      // A[0][i].  We cannot know that the user isn't doing invalid things like
528      // allowing i to index an out-of-range subscript that accesses A[1].
529      //
530      // Scalar replacing *just* the outer index of the array is probably not
531      // going to be a win anyway, so just give up.
532      for (++I; I != E && (isa<ArrayType>(*I) || isa<VectorType>(*I)); ++I) {
533        uint64_t NumElements;
534        if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*I))
535          NumElements = SubArrayTy->getNumElements();
536        else
537          NumElements = cast<VectorType>(*I)->getNumElements();
538
539        ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
540        if (!IdxVal) return MarkUnsafe(Info);
541        if (IdxVal->getZExtValue() >= NumElements)
542          return MarkUnsafe(Info);
543        IsAllZeroIndices &= IdxVal->isZero();
544      }
545
546    } else {
547      IsAllZeroIndices = 0;
548
549      // If this is an array index and the index is not constant, we cannot
550      // promote... that is unless the array has exactly one or two elements in
551      // it, in which case we CAN promote it, but we have to canonicalize this
552      // out if this is the only problem.
553      if ((NumElements == 1 || NumElements == 2) &&
554          AllUsersAreLoads(GEPI)) {
555        Info.needsCanon = true;
556        return;  // Canonicalization required!
557      }
558      return MarkUnsafe(Info);
559    }
560  }
561
562  // If there are any non-simple uses of this getelementptr, make sure to reject
563  // them.
564  return isSafeElementUse(GEPI, IsAllZeroIndices, AI, Info);
565}
566
567/// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
568/// intrinsic can be promoted by SROA.  At this point, we know that the operand
569/// of the memintrinsic is a pointer to the beginning of the allocation.
570void SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
571                                          unsigned OpNo, AllocaInfo &Info) {
572  // If not constant length, give up.
573  ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
574  if (!Length) return MarkUnsafe(Info);
575
576  // If not the whole aggregate, give up.
577  const TargetData &TD = getAnalysis<TargetData>();
578  if (Length->getZExtValue() !=
579      TD.getABITypeSize(AI->getType()->getElementType()))
580    return MarkUnsafe(Info);
581
582  // We only know about memcpy/memset/memmove.
583  if (!isa<MemCpyInst>(MI) && !isa<MemSetInst>(MI) && !isa<MemMoveInst>(MI))
584    return MarkUnsafe(Info);
585
586  // Otherwise, we can transform it.  Determine whether this is a memcpy/set
587  // into or out of the aggregate.
588  if (OpNo == 1)
589    Info.isMemCpyDst = true;
590  else {
591    assert(OpNo == 2);
592    Info.isMemCpySrc = true;
593  }
594}
595
596/// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
597/// are
598void SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI,
599                                          AllocaInfo &Info) {
600  for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
601       UI != E; ++UI) {
602    if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
603      isSafeUseOfBitCastedAllocation(BCU, AI, Info);
604    } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
605      isSafeMemIntrinsicOnAllocation(MI, AI, UI.getOperandNo(), Info);
606    } else {
607      return MarkUnsafe(Info);
608    }
609    if (Info.isUnsafe) return;
610  }
611}
612
613/// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
614/// to its first element.  Transform users of the cast to use the new values
615/// instead.
616void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
617                                      SmallVector<AllocaInst*, 32> &NewElts) {
618  Constant *Zero = Constant::getNullValue(Type::Int32Ty);
619  const TargetData &TD = getAnalysis<TargetData>();
620
621  Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
622  while (UI != UE) {
623    if (BitCastInst *BCU = dyn_cast<BitCastInst>(*UI)) {
624      RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
625      ++UI;
626      BCU->eraseFromParent();
627      continue;
628    }
629
630    // Otherwise, must be memcpy/memmove/memset of the entire aggregate.  Split
631    // into one per element.
632    MemIntrinsic *MI = dyn_cast<MemIntrinsic>(*UI);
633
634    // If it's not a mem intrinsic, it must be some other user of a gep of the
635    // first pointer.  Just leave these alone.
636    if (!MI) {
637      ++UI;
638      continue;
639    }
640
641    // If this is a memcpy/memmove, construct the other pointer as the
642    // appropriate type.
643    Value *OtherPtr = 0;
644    if (MemCpyInst *MCI = dyn_cast<MemCpyInst>(MI)) {
645      if (BCInst == MCI->getRawDest())
646        OtherPtr = MCI->getRawSource();
647      else {
648        assert(BCInst == MCI->getRawSource());
649        OtherPtr = MCI->getRawDest();
650      }
651    } else if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
652      if (BCInst == MMI->getRawDest())
653        OtherPtr = MMI->getRawSource();
654      else {
655        assert(BCInst == MMI->getRawSource());
656        OtherPtr = MMI->getRawDest();
657      }
658    }
659
660    // If there is an other pointer, we want to convert it to the same pointer
661    // type as AI has, so we can GEP through it.
662    if (OtherPtr) {
663      // It is likely that OtherPtr is a bitcast, if so, remove it.
664      if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
665        OtherPtr = BC->getOperand(0);
666      if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
667        if (BCE->getOpcode() == Instruction::BitCast)
668          OtherPtr = BCE->getOperand(0);
669
670      // If the pointer is not the right type, insert a bitcast to the right
671      // type.
672      if (OtherPtr->getType() != AI->getType())
673        OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
674                                   MI);
675    }
676
677    // Process each element of the aggregate.
678    Value *TheFn = MI->getOperand(0);
679    const Type *BytePtrTy = MI->getRawDest()->getType();
680    bool SROADest = MI->getRawDest() == BCInst;
681
682    for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
683      // If this is a memcpy/memmove, emit a GEP of the other element address.
684      Value *OtherElt = 0;
685      if (OtherPtr) {
686        Value *Idx[2] = { Zero, ConstantInt::get(Type::Int32Ty, i) };
687        OtherElt = GetElementPtrInst::Create(OtherPtr, Idx, Idx + 2,
688                                           OtherPtr->getNameStr()+"."+utostr(i),
689                                             MI);
690      }
691
692      Value *EltPtr = NewElts[i];
693      const Type *EltTy =cast<PointerType>(EltPtr->getType())->getElementType();
694
695      // If we got down to a scalar, insert a load or store as appropriate.
696      if (EltTy->isSingleValueType()) {
697        if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
698          Value *Elt = new LoadInst(SROADest ? OtherElt : EltPtr, "tmp",
699                                    MI);
700          new StoreInst(Elt, SROADest ? EltPtr : OtherElt, MI);
701          continue;
702        } else {
703          assert(isa<MemSetInst>(MI));
704
705          // If the stored element is zero (common case), just store a null
706          // constant.
707          Constant *StoreVal;
708          if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
709            if (CI->isZero()) {
710              StoreVal = Constant::getNullValue(EltTy);  // 0.0, null, 0, <0,0>
711            } else {
712              // If EltTy is a vector type, get the element type.
713              const Type *ValTy = EltTy;
714              if (const VectorType *VTy = dyn_cast<VectorType>(ValTy))
715                ValTy = VTy->getElementType();
716
717              // Construct an integer with the right value.
718              unsigned EltSize = TD.getTypeSizeInBits(ValTy);
719              APInt OneVal(EltSize, CI->getZExtValue());
720              APInt TotalVal(OneVal);
721              // Set each byte.
722              for (unsigned i = 0; 8*i < EltSize; ++i) {
723                TotalVal = TotalVal.shl(8);
724                TotalVal |= OneVal;
725              }
726
727              // Convert the integer value to the appropriate type.
728              StoreVal = ConstantInt::get(TotalVal);
729              if (isa<PointerType>(ValTy))
730                StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
731              else if (ValTy->isFloatingPoint())
732                StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
733              assert(StoreVal->getType() == ValTy && "Type mismatch!");
734
735              // If the requested value was a vector constant, create it.
736              if (EltTy != ValTy) {
737                unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
738                SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
739                StoreVal = ConstantVector::get(&Elts[0], NumElts);
740              }
741            }
742            new StoreInst(StoreVal, EltPtr, MI);
743            continue;
744          }
745          // Otherwise, if we're storing a byte variable, use a memset call for
746          // this element.
747        }
748      }
749
750      // Cast the element pointer to BytePtrTy.
751      if (EltPtr->getType() != BytePtrTy)
752        EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
753
754      // Cast the other pointer (if we have one) to BytePtrTy.
755      if (OtherElt && OtherElt->getType() != BytePtrTy)
756        OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
757                                   MI);
758
759      unsigned EltSize = TD.getABITypeSize(EltTy);
760
761      // Finally, insert the meminst for this element.
762      if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
763        Value *Ops[] = {
764          SROADest ? EltPtr : OtherElt,  // Dest ptr
765          SROADest ? OtherElt : EltPtr,  // Src ptr
766          ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
767          Zero  // Align
768        };
769        CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
770      } else {
771        assert(isa<MemSetInst>(MI));
772        Value *Ops[] = {
773          EltPtr, MI->getOperand(2),  // Dest, Value,
774          ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
775          Zero  // Align
776        };
777        CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
778      }
779    }
780
781    // Finally, MI is now dead, as we've modified its actions to occur on all of
782    // the elements of the aggregate.
783    ++UI;
784    MI->eraseFromParent();
785  }
786}
787
788/// HasPadding - Return true if the specified type has any structure or
789/// alignment padding, false otherwise.
790static bool HasPadding(const Type *Ty, const TargetData &TD) {
791  if (const StructType *STy = dyn_cast<StructType>(Ty)) {
792    const StructLayout *SL = TD.getStructLayout(STy);
793    unsigned PrevFieldBitOffset = 0;
794    for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
795      unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
796
797      // Padding in sub-elements?
798      if (HasPadding(STy->getElementType(i), TD))
799        return true;
800
801      // Check to see if there is any padding between this element and the
802      // previous one.
803      if (i) {
804        unsigned PrevFieldEnd =
805        PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
806        if (PrevFieldEnd < FieldBitOffset)
807          return true;
808      }
809
810      PrevFieldBitOffset = FieldBitOffset;
811    }
812
813    //  Check for tail padding.
814    if (unsigned EltCount = STy->getNumElements()) {
815      unsigned PrevFieldEnd = PrevFieldBitOffset +
816                   TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
817      if (PrevFieldEnd < SL->getSizeInBits())
818        return true;
819    }
820
821  } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
822    return HasPadding(ATy->getElementType(), TD);
823  } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
824    return HasPadding(VTy->getElementType(), TD);
825  }
826  return TD.getTypeSizeInBits(Ty) != TD.getABITypeSizeInBits(Ty);
827}
828
829/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
830/// an aggregate can be broken down into elements.  Return 0 if not, 3 if safe,
831/// or 1 if safe after canonicalization has been performed.
832///
833int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
834  // Loop over the use list of the alloca.  We can only transform it if all of
835  // the users are safe to transform.
836  AllocaInfo Info;
837
838  for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
839       I != E; ++I) {
840    isSafeUseOfAllocation(cast<Instruction>(*I), AI, Info);
841    if (Info.isUnsafe) {
842      DOUT << "Cannot transform: " << *AI << "  due to user: " << **I;
843      return 0;
844    }
845  }
846
847  // Okay, we know all the users are promotable.  If the aggregate is a memcpy
848  // source and destination, we have to be careful.  In particular, the memcpy
849  // could be moving around elements that live in structure padding of the LLVM
850  // types, but may actually be used.  In these cases, we refuse to promote the
851  // struct.
852  if (Info.isMemCpySrc && Info.isMemCpyDst &&
853      HasPadding(AI->getType()->getElementType(), getAnalysis<TargetData>()))
854    return 0;
855
856  // If we require cleanup, return 1, otherwise return 3.
857  return Info.needsCanon ? 1 : 3;
858}
859
860/// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified
861/// allocation, but only if cleaned up, perform the cleanups required.
862void SROA::CanonicalizeAllocaUsers(AllocationInst *AI) {
863  // At this point, we know that the end result will be SROA'd and promoted, so
864  // we can insert ugly code if required so long as sroa+mem2reg will clean it
865  // up.
866  for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
867       UI != E; ) {
868    GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI++);
869    if (!GEPI) continue;
870    gep_type_iterator I = gep_type_begin(GEPI);
871    ++I;
872
873    if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
874      uint64_t NumElements = AT->getNumElements();
875
876      if (!isa<ConstantInt>(I.getOperand())) {
877        if (NumElements == 1) {
878          GEPI->setOperand(2, Constant::getNullValue(Type::Int32Ty));
879        } else {
880          assert(NumElements == 2 && "Unhandled case!");
881          // All users of the GEP must be loads.  At each use of the GEP, insert
882          // two loads of the appropriate indexed GEP and select between them.
883          Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(),
884                              Constant::getNullValue(I.getOperand()->getType()),
885             "isone", GEPI);
886          // Insert the new GEP instructions, which are properly indexed.
887          SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
888          Indices[1] = Constant::getNullValue(Type::Int32Ty);
889          Value *ZeroIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
890                                                     Indices.begin(),
891                                                     Indices.end(),
892                                                     GEPI->getName()+".0", GEPI);
893          Indices[1] = ConstantInt::get(Type::Int32Ty, 1);
894          Value *OneIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
895                                                    Indices.begin(),
896                                                    Indices.end(),
897                                                    GEPI->getName()+".1", GEPI);
898          // Replace all loads of the variable index GEP with loads from both
899          // indexes and a select.
900          while (!GEPI->use_empty()) {
901            LoadInst *LI = cast<LoadInst>(GEPI->use_back());
902            Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
903            Value *One  = new LoadInst(OneIdx , LI->getName()+".1", LI);
904            Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI);
905            LI->replaceAllUsesWith(R);
906            LI->eraseFromParent();
907          }
908          GEPI->eraseFromParent();
909        }
910      }
911    }
912  }
913}
914
915/// MergeInType - Add the 'In' type to the accumulated type so far.  If the
916/// types are incompatible, return true, otherwise update Accum and return
917/// false.
918///
919/// There are three cases we handle here:
920///   1) An effectively-integer union, where the pieces are stored into as
921///      smaller integers (common with byte swap and other idioms).
922///   2) A union of vector types of the same size and potentially its elements.
923///      Here we turn element accesses into insert/extract element operations.
924///   3) A union of scalar types, such as int/float or int/pointer.  Here we
925///      merge together into integers, allowing the xform to work with #1 as
926///      well.
927static bool MergeInType(const Type *In, const Type *&Accum,
928                        const TargetData &TD) {
929  // If this is our first type, just use it.
930  const VectorType *PTy;
931  if (Accum == Type::VoidTy || In == Accum) {
932    Accum = In;
933  } else if (In == Type::VoidTy) {
934    // Noop.
935  } else if (In->isInteger() && Accum->isInteger()) {   // integer union.
936    // Otherwise pick whichever type is larger.
937    if (cast<IntegerType>(In)->getBitWidth() >
938        cast<IntegerType>(Accum)->getBitWidth())
939      Accum = In;
940  } else if (isa<PointerType>(In) && isa<PointerType>(Accum)) {
941    // Pointer unions just stay as one of the pointers.
942  } else if (isa<VectorType>(In) || isa<VectorType>(Accum)) {
943    if ((PTy = dyn_cast<VectorType>(Accum)) &&
944        PTy->getElementType() == In) {
945      // Accum is a vector, and we are accessing an element: ok.
946    } else if ((PTy = dyn_cast<VectorType>(In)) &&
947               PTy->getElementType() == Accum) {
948      // In is a vector, and accum is an element: ok, remember In.
949      Accum = In;
950    } else if ((PTy = dyn_cast<VectorType>(In)) && isa<VectorType>(Accum) &&
951               PTy->getBitWidth() == cast<VectorType>(Accum)->getBitWidth()) {
952      // Two vectors of the same size: keep Accum.
953    } else {
954      // Cannot insert an short into a <4 x int> or handle
955      // <2 x int> -> <4 x int>
956      return true;
957    }
958  } else {
959    // Pointer/FP/Integer unions merge together as integers.
960    switch (Accum->getTypeID()) {
961    case Type::PointerTyID: Accum = TD.getIntPtrType(); break;
962    case Type::FloatTyID:   Accum = Type::Int32Ty; break;
963    case Type::DoubleTyID:  Accum = Type::Int64Ty; break;
964    case Type::X86_FP80TyID:  return true;
965    case Type::FP128TyID: return true;
966    case Type::PPC_FP128TyID: return true;
967    default:
968      assert(Accum->isInteger() && "Unknown FP type!");
969      break;
970    }
971
972    switch (In->getTypeID()) {
973    case Type::PointerTyID: In = TD.getIntPtrType(); break;
974    case Type::FloatTyID:   In = Type::Int32Ty; break;
975    case Type::DoubleTyID:  In = Type::Int64Ty; break;
976    case Type::X86_FP80TyID:  return true;
977    case Type::FP128TyID: return true;
978    case Type::PPC_FP128TyID: return true;
979    default:
980      assert(In->isInteger() && "Unknown FP type!");
981      break;
982    }
983    return MergeInType(In, Accum, TD);
984  }
985  return false;
986}
987
988/// getUIntAtLeastAsBigAs - Return an unsigned integer type that is at least
989/// as big as the specified type.  If there is no suitable type, this returns
990/// null.
991const Type *getUIntAtLeastAsBigAs(unsigned NumBits) {
992  if (NumBits > 64) return 0;
993  if (NumBits > 32) return Type::Int64Ty;
994  if (NumBits > 16) return Type::Int32Ty;
995  if (NumBits > 8) return Type::Int16Ty;
996  return Type::Int8Ty;
997}
998
999/// CanConvertToScalar - V is a pointer.  If we can convert the pointee to a
1000/// single scalar integer type, return that type.  Further, if the use is not
1001/// a completely trivial use that mem2reg could promote, set IsNotTrivial.  If
1002/// there are no uses of this pointer, return Type::VoidTy to differentiate from
1003/// failure.
1004///
1005const Type *SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial) {
1006  const Type *UsedType = Type::VoidTy; // No uses, no forced type.
1007  const TargetData &TD = getAnalysis<TargetData>();
1008  const PointerType *PTy = cast<PointerType>(V->getType());
1009
1010  for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1011    Instruction *User = cast<Instruction>(*UI);
1012
1013    if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1014      // FIXME: Loads of a first class aggregrate value could be converted to a
1015      // series of loads and insertvalues
1016      if (!LI->getType()->isSingleValueType())
1017        return 0;
1018
1019      if (MergeInType(LI->getType(), UsedType, TD))
1020        return 0;
1021
1022    } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1023      // Storing the pointer, not into the value?
1024      if (SI->getOperand(0) == V) return 0;
1025
1026      // FIXME: Stores of a first class aggregrate value could be converted to a
1027      // series of extractvalues and stores
1028      if (!SI->getOperand(0)->getType()->isSingleValueType())
1029        return 0;
1030
1031      // NOTE: We could handle storing of FP imms into integers here!
1032
1033      if (MergeInType(SI->getOperand(0)->getType(), UsedType, TD))
1034        return 0;
1035    } else if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
1036      IsNotTrivial = true;
1037      const Type *SubTy = CanConvertToScalar(CI, IsNotTrivial);
1038      if (!SubTy || MergeInType(SubTy, UsedType, TD)) return 0;
1039    } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1040      // Check to see if this is stepping over an element: GEP Ptr, int C
1041      if (GEP->getNumOperands() == 2 && isa<ConstantInt>(GEP->getOperand(1))) {
1042        unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
1043        unsigned ElSize = TD.getABITypeSize(PTy->getElementType());
1044        unsigned BitOffset = Idx*ElSize*8;
1045        if (BitOffset > 64 || !isPowerOf2_32(ElSize)) return 0;
1046
1047        IsNotTrivial = true;
1048        const Type *SubElt = CanConvertToScalar(GEP, IsNotTrivial);
1049        if (SubElt == 0) return 0;
1050        if (SubElt != Type::VoidTy && SubElt->isInteger()) {
1051          const Type *NewTy =
1052            getUIntAtLeastAsBigAs(TD.getABITypeSizeInBits(SubElt)+BitOffset);
1053          if (NewTy == 0 || MergeInType(NewTy, UsedType, TD)) return 0;
1054          continue;
1055        }
1056      } else if (GEP->getNumOperands() == 3 &&
1057                 isa<ConstantInt>(GEP->getOperand(1)) &&
1058                 isa<ConstantInt>(GEP->getOperand(2)) &&
1059                 cast<ConstantInt>(GEP->getOperand(1))->isZero()) {
1060        // We are stepping into an element, e.g. a structure or an array:
1061        // GEP Ptr, int 0, uint C
1062        const Type *AggTy = PTy->getElementType();
1063        unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
1064
1065        if (const ArrayType *ATy = dyn_cast<ArrayType>(AggTy)) {
1066          if (Idx >= ATy->getNumElements()) return 0;  // Out of range.
1067        } else if (const VectorType *VectorTy = dyn_cast<VectorType>(AggTy)) {
1068          // Getting an element of the vector.
1069          if (Idx >= VectorTy->getNumElements()) return 0;  // Out of range.
1070
1071          // Merge in the vector type.
1072          if (MergeInType(VectorTy, UsedType, TD)) return 0;
1073
1074          const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
1075          if (SubTy == 0) return 0;
1076
1077          if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
1078            return 0;
1079
1080          // We'll need to change this to an insert/extract element operation.
1081          IsNotTrivial = true;
1082          continue;    // Everything looks ok
1083
1084        } else if (isa<StructType>(AggTy)) {
1085          // Structs are always ok.
1086        } else {
1087          return 0;
1088        }
1089        const Type *NTy = getUIntAtLeastAsBigAs(TD.getABITypeSizeInBits(AggTy));
1090        if (NTy == 0 || MergeInType(NTy, UsedType, TD)) return 0;
1091        const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
1092        if (SubTy == 0) return 0;
1093        if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
1094          return 0;
1095        continue;    // Everything looks ok
1096      }
1097      return 0;
1098    } else {
1099      // Cannot handle this!
1100      return 0;
1101    }
1102  }
1103
1104  return UsedType;
1105}
1106
1107/// ConvertToScalar - The specified alloca passes the CanConvertToScalar
1108/// predicate and is non-trivial.  Convert it to something that can be trivially
1109/// promoted into a register by mem2reg.
1110void SROA::ConvertToScalar(AllocationInst *AI, const Type *ActualTy) {
1111  DOUT << "CONVERT TO SCALAR: " << *AI << "  TYPE = "
1112       << *ActualTy << "\n";
1113  ++NumConverted;
1114
1115  BasicBlock *EntryBlock = AI->getParent();
1116  assert(EntryBlock == &EntryBlock->getParent()->getEntryBlock() &&
1117         "Not in the entry block!");
1118  EntryBlock->getInstList().remove(AI);  // Take the alloca out of the program.
1119
1120  // Create and insert the alloca.
1121  AllocaInst *NewAI = new AllocaInst(ActualTy, 0, AI->getName(),
1122                                     EntryBlock->begin());
1123  ConvertUsesToScalar(AI, NewAI, 0);
1124  delete AI;
1125}
1126
1127
1128/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
1129/// directly.  This happens when we are converting an "integer union" to a
1130/// single integer scalar, or when we are converting a "vector union" to a
1131/// vector with insert/extractelement instructions.
1132///
1133/// Offset is an offset from the original alloca, in bits that need to be
1134/// shifted to the right.  By the end of this, there should be no uses of Ptr.
1135void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset) {
1136  while (!Ptr->use_empty()) {
1137    Instruction *User = cast<Instruction>(Ptr->use_back());
1138
1139    if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1140      Value *NV = ConvertUsesOfLoadToScalar(LI, NewAI, Offset);
1141      LI->replaceAllUsesWith(NV);
1142      LI->eraseFromParent();
1143    } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1144      assert(SI->getOperand(0) != Ptr && "Consistency error!");
1145
1146      Value *SV = ConvertUsesOfStoreToScalar(SI, NewAI, Offset);
1147      new StoreInst(SV, NewAI, SI);
1148      SI->eraseFromParent();
1149
1150    } else if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
1151      ConvertUsesToScalar(CI, NewAI, Offset);
1152      CI->eraseFromParent();
1153    } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1154      const PointerType *AggPtrTy =
1155        cast<PointerType>(GEP->getOperand(0)->getType());
1156      const TargetData &TD = getAnalysis<TargetData>();
1157      unsigned AggSizeInBits =
1158        TD.getABITypeSizeInBits(AggPtrTy->getElementType());
1159
1160      // Check to see if this is stepping over an element: GEP Ptr, int C
1161      unsigned NewOffset = Offset;
1162      if (GEP->getNumOperands() == 2) {
1163        unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
1164        unsigned BitOffset = Idx*AggSizeInBits;
1165
1166        NewOffset += BitOffset;
1167      } else if (GEP->getNumOperands() == 3) {
1168        // We know that operand #2 is zero.
1169        unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
1170        const Type *AggTy = AggPtrTy->getElementType();
1171        if (const SequentialType *SeqTy = dyn_cast<SequentialType>(AggTy)) {
1172          unsigned ElSizeBits =
1173            TD.getABITypeSizeInBits(SeqTy->getElementType());
1174
1175          NewOffset += ElSizeBits*Idx;
1176        } else if (const StructType *STy = dyn_cast<StructType>(AggTy)) {
1177          unsigned EltBitOffset =
1178            TD.getStructLayout(STy)->getElementOffsetInBits(Idx);
1179
1180          NewOffset += EltBitOffset;
1181        } else {
1182          assert(0 && "Unsupported operation!");
1183          abort();
1184        }
1185      } else {
1186        assert(0 && "Unsupported operation!");
1187        abort();
1188      }
1189      ConvertUsesToScalar(GEP, NewAI, NewOffset);
1190      GEP->eraseFromParent();
1191    } else {
1192      assert(0 && "Unsupported operation!");
1193      abort();
1194    }
1195  }
1196}
1197
1198/// ConvertUsesOfLoadToScalar - Convert all of the users the specified load to
1199/// use the new alloca directly, returning the value that should replace the
1200/// load.  This happens when we are converting an "integer union" to a
1201/// single integer scalar, or when we are converting a "vector union" to a
1202/// vector with insert/extractelement instructions.
1203///
1204/// Offset is an offset from the original alloca, in bits that need to be
1205/// shifted to the right.  By the end of this, there should be no uses of Ptr.
1206Value *SROA::ConvertUsesOfLoadToScalar(LoadInst *LI, AllocaInst *NewAI,
1207                                       unsigned Offset) {
1208  // The load is a bit extract from NewAI shifted right by Offset bits.
1209  Value *NV = new LoadInst(NewAI, LI->getName(), LI);
1210
1211  if (NV->getType() == LI->getType() && Offset == 0) {
1212    // We win, no conversion needed.
1213    return NV;
1214  }
1215
1216  // If the result type of the 'union' is a pointer, then this must be ptr->ptr
1217  // cast.  Anything else would result in NV being an integer.
1218  if (isa<PointerType>(NV->getType())) {
1219    assert(isa<PointerType>(LI->getType()));
1220    return new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1221  }
1222
1223  if (const VectorType *VTy = dyn_cast<VectorType>(NV->getType())) {
1224    // If the result alloca is a vector type, this is either an element
1225    // access or a bitcast to another vector type.
1226    if (isa<VectorType>(LI->getType()))
1227      return new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1228
1229    // Otherwise it must be an element access.
1230    const TargetData &TD = getAnalysis<TargetData>();
1231    unsigned Elt = 0;
1232    if (Offset) {
1233      unsigned EltSize = TD.getABITypeSizeInBits(VTy->getElementType());
1234      Elt = Offset/EltSize;
1235      Offset -= EltSize*Elt;
1236    }
1237    NV = new ExtractElementInst(NV, ConstantInt::get(Type::Int32Ty, Elt),
1238                                "tmp", LI);
1239
1240    // If we're done, return this element.
1241    if (NV->getType() == LI->getType() && Offset == 0)
1242      return NV;
1243  }
1244
1245  const IntegerType *NTy = cast<IntegerType>(NV->getType());
1246
1247  // If this is a big-endian system and the load is narrower than the
1248  // full alloca type, we need to do a shift to get the right bits.
1249  int ShAmt = 0;
1250  const TargetData &TD = getAnalysis<TargetData>();
1251  if (TD.isBigEndian()) {
1252    // On big-endian machines, the lowest bit is stored at the bit offset
1253    // from the pointer given by getTypeStoreSizeInBits.  This matters for
1254    // integers with a bitwidth that is not a multiple of 8.
1255    ShAmt = TD.getTypeStoreSizeInBits(NTy) -
1256    TD.getTypeStoreSizeInBits(LI->getType()) - Offset;
1257  } else {
1258    ShAmt = Offset;
1259  }
1260
1261  // Note: we support negative bitwidths (with shl) which are not defined.
1262  // We do this to support (f.e.) loads off the end of a structure where
1263  // only some bits are used.
1264  if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
1265    NV = BinaryOperator::CreateLShr(NV,
1266                                    ConstantInt::get(NV->getType(),ShAmt),
1267                                    LI->getName(), LI);
1268  else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
1269    NV = BinaryOperator::CreateShl(NV,
1270                                   ConstantInt::get(NV->getType(),-ShAmt),
1271                                   LI->getName(), LI);
1272
1273  // Finally, unconditionally truncate the integer to the right width.
1274  unsigned LIBitWidth = TD.getTypeSizeInBits(LI->getType());
1275  if (LIBitWidth < NTy->getBitWidth())
1276    NV = new TruncInst(NV, IntegerType::get(LIBitWidth),
1277                       LI->getName(), LI);
1278
1279  // If the result is an integer, this is a trunc or bitcast.
1280  if (isa<IntegerType>(LI->getType())) {
1281    // Should be done.
1282  } else if (LI->getType()->isFloatingPoint()) {
1283    // Just do a bitcast, we know the sizes match up.
1284    NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1285  } else {
1286    // Otherwise must be a pointer.
1287    NV = new IntToPtrInst(NV, LI->getType(), LI->getName(), LI);
1288  }
1289  assert(NV->getType() == LI->getType() && "Didn't convert right?");
1290  return NV;
1291}
1292
1293
1294/// ConvertUsesOfStoreToScalar - Convert the specified store to a load+store
1295/// pair of the new alloca directly, returning the value that should be stored
1296/// to the alloca.  This happens when we are converting an "integer union" to a
1297/// single integer scalar, or when we are converting a "vector union" to a
1298/// vector with insert/extractelement instructions.
1299///
1300/// Offset is an offset from the original alloca, in bits that need to be
1301/// shifted to the right.  By the end of this, there should be no uses of Ptr.
1302Value *SROA::ConvertUsesOfStoreToScalar(StoreInst *SI, AllocaInst *NewAI,
1303                                        unsigned Offset) {
1304
1305  // Convert the stored type to the actual type, shift it left to insert
1306  // then 'or' into place.
1307  Value *SV = SI->getOperand(0);
1308  const Type *AllocaType = NewAI->getType()->getElementType();
1309  if (SV->getType() == AllocaType && Offset == 0) {
1310    // All is well.
1311  } else if (const VectorType *PTy = dyn_cast<VectorType>(AllocaType)) {
1312    Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1313
1314    // If the result alloca is a vector type, this is either an element
1315    // access or a bitcast to another vector type.
1316    if (isa<VectorType>(SV->getType())) {
1317      SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1318    } else {
1319      // Must be an element insertion.
1320      const TargetData &TD = getAnalysis<TargetData>();
1321      unsigned Elt = Offset/TD.getABITypeSizeInBits(PTy->getElementType());
1322      SV = InsertElementInst::Create(Old, SV,
1323                                     ConstantInt::get(Type::Int32Ty, Elt),
1324                                     "tmp", SI);
1325    }
1326  } else if (isa<PointerType>(AllocaType)) {
1327    // If the alloca type is a pointer, then all the elements must be
1328    // pointers.
1329    if (SV->getType() != AllocaType)
1330      SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1331  } else {
1332    Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1333
1334    // If SV is a float, convert it to the appropriate integer type.
1335    // If it is a pointer, do the same, and also handle ptr->ptr casts
1336    // here.
1337    const TargetData &TD = getAnalysis<TargetData>();
1338    unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
1339    unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
1340    unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
1341    unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
1342    if (SV->getType()->isFloatingPoint())
1343      SV = new BitCastInst(SV, IntegerType::get(SrcWidth),
1344                           SV->getName(), SI);
1345    else if (isa<PointerType>(SV->getType()))
1346      SV = new PtrToIntInst(SV, TD.getIntPtrType(), SV->getName(), SI);
1347
1348    // Always zero extend the value if needed.
1349    if (SV->getType() != AllocaType)
1350      SV = new ZExtInst(SV, AllocaType, SV->getName(), SI);
1351
1352    // If this is a big-endian system and the store is narrower than the
1353    // full alloca type, we need to do a shift to get the right bits.
1354    int ShAmt = 0;
1355    if (TD.isBigEndian()) {
1356      // On big-endian machines, the lowest bit is stored at the bit offset
1357      // from the pointer given by getTypeStoreSizeInBits.  This matters for
1358      // integers with a bitwidth that is not a multiple of 8.
1359      ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
1360    } else {
1361      ShAmt = Offset;
1362    }
1363
1364    // Note: we support negative bitwidths (with shr) which are not defined.
1365    // We do this to support (f.e.) stores off the end of a structure where
1366    // only some bits in the structure are set.
1367    APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1368    if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1369      SV = BinaryOperator::CreateShl(SV,
1370                                     ConstantInt::get(SV->getType(), ShAmt),
1371                                     SV->getName(), SI);
1372      Mask <<= ShAmt;
1373    } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1374      SV = BinaryOperator::CreateLShr(SV,
1375                                      ConstantInt::get(SV->getType(),-ShAmt),
1376                                      SV->getName(), SI);
1377      Mask = Mask.lshr(ShAmt);
1378    }
1379
1380    // Mask out the bits we are about to insert from the old value, and or
1381    // in the new bits.
1382    if (SrcWidth != DestWidth) {
1383      assert(DestWidth > SrcWidth);
1384      Old = BinaryOperator::CreateAnd(Old, ConstantInt::get(~Mask),
1385                                      Old->getName()+".mask", SI);
1386      SV = BinaryOperator::CreateOr(Old, SV, SV->getName()+".ins", SI);
1387    }
1388  }
1389  return SV;
1390}
1391
1392
1393
1394/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1395/// some part of a constant global variable.  This intentionally only accepts
1396/// constant expressions because we don't can't rewrite arbitrary instructions.
1397static bool PointsToConstantGlobal(Value *V) {
1398  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1399    return GV->isConstant();
1400  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1401    if (CE->getOpcode() == Instruction::BitCast ||
1402        CE->getOpcode() == Instruction::GetElementPtr)
1403      return PointsToConstantGlobal(CE->getOperand(0));
1404  return false;
1405}
1406
1407/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1408/// pointer to an alloca.  Ignore any reads of the pointer, return false if we
1409/// see any stores or other unknown uses.  If we see pointer arithmetic, keep
1410/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1411/// the uses.  If we see a memcpy/memmove that targets an unoffseted pointer to
1412/// the alloca, and if the source pointer is a pointer to a constant  global, we
1413/// can optimize this.
1414static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1415                                           bool isOffset) {
1416  for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1417    if (isa<LoadInst>(*UI)) {
1418      // Ignore loads, they are always ok.
1419      continue;
1420    }
1421    if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1422      // If uses of the bitcast are ok, we are ok.
1423      if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1424        return false;
1425      continue;
1426    }
1427    if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1428      // If the GEP has all zero indices, it doesn't offset the pointer.  If it
1429      // doesn't, it does.
1430      if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1431                                         isOffset || !GEP->hasAllZeroIndices()))
1432        return false;
1433      continue;
1434    }
1435
1436    // If this is isn't our memcpy/memmove, reject it as something we can't
1437    // handle.
1438    if (!isa<MemCpyInst>(*UI) && !isa<MemMoveInst>(*UI))
1439      return false;
1440
1441    // If we already have seen a copy, reject the second one.
1442    if (TheCopy) return false;
1443
1444    // If the pointer has been offset from the start of the alloca, we can't
1445    // safely handle this.
1446    if (isOffset) return false;
1447
1448    // If the memintrinsic isn't using the alloca as the dest, reject it.
1449    if (UI.getOperandNo() != 1) return false;
1450
1451    MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1452
1453    // If the source of the memcpy/move is not a constant global, reject it.
1454    if (!PointsToConstantGlobal(MI->getOperand(2)))
1455      return false;
1456
1457    // Otherwise, the transform is safe.  Remember the copy instruction.
1458    TheCopy = MI;
1459  }
1460  return true;
1461}
1462
1463/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1464/// modified by a copy from a constant global.  If we can prove this, we can
1465/// replace any uses of the alloca with uses of the global directly.
1466Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocationInst *AI) {
1467  Instruction *TheCopy = 0;
1468  if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1469    return TheCopy;
1470  return 0;
1471}
1472