c09ad3d29833d635818af9afaaa4133e6c7914fe
[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;  // Increment BI to point to instruction to delete
54
55   // Replace all uses of the old instruction, and delete it.
56   ReplaceInstWithValue(BIL, BI, I);
57
58   // Move BI back to point to the newly inserted instruction
59   --BI;
60 }
61
62 void ReplaceInstWithInst(Instruction *From, Instruction *To) {
63   BasicBlock *BB = From->getParent();
64   BasicBlock::InstListType &BIL = BB->getInstList();
65   BasicBlock::iterator BI = find(BIL.begin(), BIL.end(), From);
66   assert(BI != BIL.end() && "Inst not in it's parents BB!");
67   ReplaceInstWithInst(BIL, BI, To);
68 }
69
70
71
72 // getStructOffsetType - Return a vector of offsets that are to be used to index
73 // into the specified struct type to get as close as possible to index as we
74 // can.  Note that it is possible that we cannot get exactly to Offset, in which
75 // case we update offset to be the offset we actually obtained.  The resultant
76 // leaf type is returned.
77 //
78 // If StopEarly is set to true (the default), the first object with the
79 // specified type is returned, even if it is a struct type itself.  In this
80 // case, this routine will not drill down to the leaf type.  Set StopEarly to
81 // false if you want a leaf
82 //
83 const Type *getStructOffsetType(const Type *Ty, unsigned &Offset,
84                                 std::vector<Value*> &Offsets,
85                                 bool StopEarly = true) {
86   if (Offset == 0 && StopEarly && !Offsets.empty())
87     return Ty;    // Return the leaf type
88
89   unsigned ThisOffset;
90   const Type *NextType;
91   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
92     assert(Offset < TD.getTypeSize(STy) && "Offset not in composite!");
93     const StructLayout *SL = TD.getStructLayout(STy);
94
95     // This loop terminates always on a 0 <= i < MemberOffsets.size()
96     unsigned i;
97     for (i = 0; i < SL->MemberOffsets.size()-1; ++i)
98       if (Offset >= SL->MemberOffsets[i] && Offset <  SL->MemberOffsets[i+1])
99         break;
100   
101     assert(Offset >= SL->MemberOffsets[i] &&
102            (i == SL->MemberOffsets.size()-1 || Offset <SL->MemberOffsets[i+1]));
103     
104     // Make sure to save the current index...
105     Offsets.push_back(ConstantUInt::get(Type::UByteTy, i));
106     ThisOffset = SL->MemberOffsets[i];
107     NextType = STy->getElementTypes()[i];
108   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
109     assert(Offset < TD.getTypeSize(ATy) && "Offset not in composite!");
110
111     NextType = ATy->getElementType();
112     unsigned ChildSize = TD.getTypeSize(NextType);
113     Offsets.push_back(ConstantUInt::get(Type::UIntTy, Offset/ChildSize));
114     ThisOffset = (Offset/ChildSize)*ChildSize;
115   } else {
116     Offset = 0;   // Return the offset that we were able to acheive
117     return Ty;    // Return the leaf type
118   }
119
120   unsigned SubOffs = Offset - ThisOffset;
121   const Type *LeafTy = getStructOffsetType(NextType, SubOffs,
122                                            Offsets, StopEarly);
123   Offset = ThisOffset + SubOffs;
124   return LeafTy;
125 }
126
127 // ConvertableToGEP - This function returns true if the specified value V is
128 // a valid index into a pointer of type Ty.  If it is valid, Idx is filled in
129 // with the values that would be appropriate to make this a getelementptr
130 // instruction.  The type returned is the root type that the GEP would point to
131 //
132 const Type *ConvertableToGEP(const Type *Ty, Value *OffsetVal,
133                              std::vector<Value*> &Indices,
134                              BasicBlock::iterator *BI = 0) {
135   const CompositeType *CompTy = dyn_cast<CompositeType>(Ty);
136   if (CompTy == 0) return 0;
137
138   // See if the cast is of an integer expression that is either a constant,
139   // or a value scaled by some amount with a possible offset.
140   //
141   analysis::ExprType Expr = analysis::ClassifyExpression(OffsetVal);
142
143   // Get the offset and scale now...
144   // A scale of zero with Expr.Var != 0 means a scale of 1.
145   //
146   // TODO: Handle negative offsets for C code like this:
147   //   for (unsigned i = 12; i < 14; ++i) x[j*i-12] = ...
148   unsigned Offset = 0;
149   int Scale = 0;
150
151   // Get the offset value if it exists...
152   if (Expr.Offset) {
153     int Val = getConstantValue(Expr.Offset);
154     if (Val < 0) return false;  // Don't mess with negative offsets
155     Offset = (unsigned)Val;
156   }
157
158   // Get the scale value if it exists...
159   if (Expr.Scale) Scale = getConstantValue(Expr.Scale);
160   if (Expr.Var && Scale == 0) Scale = 1;   // Scale != 0 if Expr.Var != 0
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)
175         return 0; // No progress.  :(
176       Offset -= ActualOffset;
177     } else {
178       const Type *ElTy = cast<SequentialType>(CompTy)->getElementType();
179       if (!ElTy->isSized())
180         return 0; // Type is unreasonable... escape!
181       unsigned ElSize = TD.getTypeSize(ElTy);
182       int ElSizeS = (int)ElSize;
183
184       // See if the user is indexing into a different cell of this array...
185       if (Scale && (Scale >= ElSizeS || -Scale >= ElSizeS)) {
186         // A scale n*ElSize might occur if we are not stepping through
187         // array by one.  In this case, we will have to insert math to munge
188         // the index.
189         //
190         int ScaleAmt = Scale/ElSizeS;
191         if (Scale-ScaleAmt*ElSizeS)
192           return 0;  // Didn't scale by a multiple of element size, bail out
193         Scale = 0;   // Scale is consumed
194
195         unsigned Index = Offset/ElSize;       // is zero unless Offset > ElSize
196         Offset -= Index*ElSize;               // Consume part of the offset
197
198         if (BI) {              // Generate code?
199           BasicBlock *BB = (**BI)->getParent();
200           if (Expr.Var->getType() != Type::UIntTy) {
201             CastInst *IdxCast = new CastInst(Expr.Var, Type::UIntTy);
202             if (Expr.Var->hasName())
203               IdxCast->setName(Expr.Var->getName()+"-idxcast");
204             *BI = BB->getInstList().insert(*BI, IdxCast)+1;
205             Expr.Var = IdxCast;
206           }
207
208           if (ScaleAmt && ScaleAmt != 1) {
209             // If we have to scale up our index, do so now
210             Value *ScaleAmtVal = ConstantUInt::get(Type::UIntTy,
211                                                    (unsigned)ScaleAmt);
212             Instruction *Scaler = BinaryOperator::create(Instruction::Mul,
213                                                          Expr.Var, ScaleAmtVal);
214             if (Expr.Var->hasName())
215               Scaler->setName(Expr.Var->getName()+"-scale");
216
217             *BI = BB->getInstList().insert(*BI, Scaler)+1;
218             Expr.Var = Scaler;
219           }
220
221           if (Index) {  // Add an offset to the index
222             Value *IndexAmt = ConstantUInt::get(Type::UIntTy, Index);
223             Instruction *Offseter = BinaryOperator::create(Instruction::Add,
224                                                            Expr.Var, IndexAmt);
225             if (Expr.Var->hasName())
226               Offseter->setName(Expr.Var->getName()+"-offset");
227             *BI = BB->getInstList().insert(*BI, Offseter)+1;
228             Expr.Var = Offseter;
229           }
230         }
231
232         Indices.push_back(Expr.Var);
233         Expr.Var = 0;
234       } else if (Offset >= ElSize) {
235         // Calculate the index that we are entering into the array cell with
236         unsigned Index = Offset/ElSize;
237         Indices.push_back(ConstantUInt::get(Type::UIntTy, Index));
238         Offset -= Index*ElSize;               // Consume part of the offset
239
240       } else if (isa<ArrayType>(CompTy) || Indices.empty()) {
241         // Must be indexing a small amount into the first cell of the array
242         // Just index into element zero of the array here.
243         //
244         Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
245       } else {
246         return 0;  // Hrm. wierd, can't handle this case.  Bail
247       }
248       NextTy = ElTy;
249     }
250   } while (Offset || Scale);    // Go until we're done!
251
252   return NextTy;
253 }