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