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