We were not correctly burrowing down multiple levels to get to a leaf. Fix this now
[oota-llvm.git] / lib / Transforms / TransformInternals.cpp
1 //===-- TransformInternals.cpp - Implement shared functions for transforms --=//
2 //
3 //  This file defines shared functions used by the different components of the
4 //  Transforms library.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #include "TransformInternals.h"
9 #include "llvm/Method.h"
10 #include "llvm/Type.h"
11 #include "llvm/ConstantVals.h"
12 #include "llvm/Analysis/Expressions.h"
13 #include "llvm/iOther.h"
14 #include <algorithm>
15
16 // TargetData Hack: Eventually we will have annotations given to us by the
17 // backend so that we know stuff about type size and alignments.  For now
18 // though, just use this, because it happens to match the model that GCC uses.
19 //
20 const TargetData TD("LevelRaise: Should be GCC though!");
21
22 // ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
23 // with a value, then remove and delete the original instruction.
24 //
25 void ReplaceInstWithValue(BasicBlock::InstListType &BIL,
26                           BasicBlock::iterator &BI, Value *V) {
27   Instruction *I = *BI;
28   // Replaces all of the uses of the instruction with uses of the value
29   I->replaceAllUsesWith(V);
30
31   // Remove the unneccesary instruction now...
32   BIL.remove(BI);
33
34   // Make sure to propogate a name if there is one already...
35   if (I->hasName() && !V->hasName())
36     V->setName(I->getName(), BIL.getParent()->getSymbolTable());
37
38   // Remove the dead instruction now...
39   delete I;
40 }
41
42
43 // ReplaceInstWithInst - Replace the instruction specified by BI with the
44 // instruction specified by I.  The original instruction is deleted and BI is
45 // updated to point to the new instruction.
46 //
47 void ReplaceInstWithInst(BasicBlock::InstListType &BIL,
48                          BasicBlock::iterator &BI, Instruction *I) {
49   assert(I->getParent() == 0 &&
50          "ReplaceInstWithInst: Instruction already inserted into basic block!");
51
52   // Insert the new instruction into the basic block...
53   BI = BIL.insert(BI, I)+1;
54
55   // Replace all uses of the old instruction, and delete it.
56   ReplaceInstWithValue(BIL, BI, I);
57
58   // Reexamine the instruction just inserted next time around the cleanup pass
59   // loop.
60   --BI;
61 }
62
63 void ReplaceInstWithInst(Instruction *From, Instruction *To) {
64   BasicBlock *BB = From->getParent();
65   BasicBlock::InstListType &BIL = BB->getInstList();
66   BasicBlock::iterator BI = find(BIL.begin(), BIL.end(), From);
67   assert(BI != BIL.end() && "Inst not in it's parents BB!");
68   ReplaceInstWithInst(BIL, BI, To);
69 }
70
71
72
73 // getStructOffsetType - Return a vector of offsets that are to be used to index
74 // into the specified struct type to get as close as possible to index as we
75 // can.  Note that it is possible that we cannot get exactly to Offset, in which
76 // case we update offset to be the offset we actually obtained.  The resultant
77 // leaf type is returned.
78 //
79 // If StopEarly is set to true (the default), the first object with the
80 // specified type is returned, even if it is a struct type itself.  In this
81 // case, this routine will not drill down to the leaf type.  Set StopEarly to
82 // false if you want a leaf
83 //
84 const Type *getStructOffsetType(const Type *Ty, unsigned &Offset,
85                                 std::vector<Value*> &Offsets,
86                                 bool StopEarly = true) {
87   if (Offset == 0 && StopEarly && !Offsets.empty())
88     return Ty;    // Return the leaf type
89
90   unsigned ThisOffset;
91   const Type *NextType;
92   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
93     assert(Offset < TD.getTypeSize(STy) && "Offset not in composite!");
94     const StructLayout *SL = TD.getStructLayout(STy);
95
96     // This loop terminates always on a 0 <= i < MemberOffsets.size()
97     unsigned i;
98     for (i = 0; i < SL->MemberOffsets.size()-1; ++i)
99       if (Offset >= SL->MemberOffsets[i] && Offset <  SL->MemberOffsets[i+1])
100         break;
101   
102     assert(Offset >= SL->MemberOffsets[i] &&
103            (i == SL->MemberOffsets.size()-1 || Offset <SL->MemberOffsets[i+1]));
104     
105     // Make sure to save the current index...
106     Offsets.push_back(ConstantUInt::get(Type::UByteTy, i));
107     ThisOffset = SL->MemberOffsets[i];
108     NextType = STy->getElementTypes()[i];
109   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
110     assert(Offset < TD.getTypeSize(ATy) && "Offset not in composite!");
111
112     NextType = ATy->getElementType();
113     unsigned ChildSize = TD.getTypeSize(NextType);
114     Offsets.push_back(ConstantUInt::get(Type::UIntTy, Offset/ChildSize));
115     ThisOffset = (Offset/ChildSize)*ChildSize;
116   } else {
117     Offset = 0;   // Return the offset that we were able to acheive
118     return Ty;    // Return the leaf type
119   }
120
121   unsigned SubOffs = Offset - ThisOffset;
122   const Type *LeafTy = getStructOffsetType(NextType, SubOffs,
123                                            Offsets, StopEarly);
124   Offset = ThisOffset + SubOffs;
125   return LeafTy;
126 }
127
128 // ConvertableToGEP - This function returns true if the specified value V is
129 // a valid index into a pointer of type Ty.  If it is valid, Idx is filled in
130 // with the values that would be appropriate to make this a getelementptr
131 // instruction.  The type returned is the root type that the GEP would point to
132 //
133 const Type *ConvertableToGEP(const Type *Ty, Value *OffsetVal,
134                              std::vector<Value*> &Indices,
135                              BasicBlock::iterator *BI = 0) {
136   const CompositeType *CompTy = dyn_cast<CompositeType>(Ty);
137   if (CompTy == 0) return 0;
138
139   // See if the cast is of an integer expression that is either a constant,
140   // or a value scaled by some amount with a possible offset.
141   //
142   analysis::ExprType Expr = analysis::ClassifyExpression(OffsetVal);
143
144   // Get the offset and scale now...
145   unsigned Offset = 0, Scale = Expr.Var != 0;
146
147   // Get the offset value if it exists...
148   if (Expr.Offset) {
149     int Val = getConstantValue(Expr.Offset);
150     if (Val < 0) return false;  // Don't mess with negative offsets
151     Offset = (unsigned)Val;
152   }
153
154   // Get the scale value if it exists...
155   if (Expr.Scale) {
156     int Val = getConstantValue(Expr.Scale);
157     if (Val < 0) return false;  // Don't mess with negative scales
158     Scale = (unsigned)Val;
159     if (Scale == 1) Scale = 0;  // No interesting scale if *1
160   }
161   
162   // Loop over the Scale and Offset values, filling in the Indices vector for
163   // our final getelementptr instruction.
164   //
165   const Type *NextTy = CompTy;
166   do {
167     if (!isa<CompositeType>(NextTy))
168       return 0;  // Type must not be ready for processing...
169     CompTy = cast<CompositeType>(NextTy);
170
171     if (const StructType *StructTy = dyn_cast<StructType>(CompTy)) {
172       unsigned ActualOffset = Offset;
173       NextTy = getStructOffsetType(StructTy, ActualOffset, Indices);
174       if (StructTy == NextTy && ActualOffset == 0) return 0; // No progress.  :(
175       Offset -= ActualOffset;
176     } else {
177       const Type *ElTy = cast<SequentialType>(CompTy)->getElementType();
178       if (!ElTy->isSized()) return 0; // Type is unreasonable... escape!
179       unsigned ElSize = TD.getTypeSize(ElTy);
180
181       // See if the user is indexing into a different cell of this array...
182       if (Scale && Scale >= ElSize) {
183         // A scale n*ElSize might occur if we are not stepping through
184         // array by one.  In this case, we will have to insert math to munge
185         // the index.
186         //
187         unsigned ScaleAmt = Scale/ElSize;
188         if (Scale-ScaleAmt*ElSize)
189           return 0;  // Didn't scale by a multiple of element size, bail out
190         Scale = 0;   // Scale is consumed
191
192         unsigned Index = Offset/ElSize;       // is zero unless Offset > ElSize
193         Offset -= Index*ElSize;               // Consume part of the offset
194
195         if (BI) {              // Generate code?
196           BasicBlock *BB = (**BI)->getParent();
197           if (Expr.Var->getType() != Type::UIntTy) {
198             CastInst *IdxCast = new CastInst(Expr.Var, Type::UIntTy);
199             if (Expr.Var->hasName())
200               IdxCast->setName(Expr.Var->getName()+"-idxcast");
201             *BI = BB->getInstList().insert(*BI, IdxCast)+1;
202             Expr.Var = IdxCast;
203           }
204
205           if (ScaleAmt && ScaleAmt != 1) {
206             // If we have to scale up our index, do so now
207             Value *ScaleAmtVal = ConstantUInt::get(Type::UIntTy, ScaleAmt);
208             Instruction *Scaler = BinaryOperator::create(Instruction::Mul,
209                                                          Expr.Var,ScaleAmtVal);
210             if (Expr.Var->hasName())
211               Scaler->setName(Expr.Var->getName()+"-scale");
212
213             *BI = BB->getInstList().insert(*BI, Scaler)+1;
214             Expr.Var = Scaler;
215           }
216
217           if (Index) {  // Add an offset to the index
218             Value *IndexAmt = ConstantUInt::get(Type::UIntTy, Index);
219             Instruction *Offseter = BinaryOperator::create(Instruction::Add,
220                                                            Expr.Var, IndexAmt);
221             if (Expr.Var->hasName())
222               Offseter->setName(Expr.Var->getName()+"-offset");
223             *BI = BB->getInstList().insert(*BI, Offseter)+1;
224             Expr.Var = Offseter;
225           }
226         }
227
228         Indices.push_back(Expr.Var);
229       } else if (Offset >= ElSize) {
230         // Calculate the index that we are entering into the array cell with
231         unsigned Index = Offset/ElSize;
232         Indices.push_back(ConstantUInt::get(Type::UIntTy, Index));
233         Offset -= Index*ElSize;               // Consume part of the offset
234
235       } else if (!isa<PointerType>(CompTy) || CompTy == Ty) {
236         // Must be indexing a small amount into the first cell of the array
237         // Just index into element zero of the array here.
238         //
239         Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
240       } else {
241         return 0;  // Hrm. wierd, can't handle this case.  Bail
242       }
243       NextTy = ElTy;
244     }
245   } while (Offset || Scale);    // Go until we're done!
246
247   return NextTy;
248 }