blob: 9ea053e040b0cfb248a3e370da1b23d6fb49add1 [file] [log] [blame]
Chris Lattner59cd9f12001-11-04 23:24:06 +00001//===-- 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"
Chris Lattnere9bb2df2001-12-03 22:26:30 +000011#include "llvm/ConstantVals.h"
Chris Lattner89a1c802001-11-26 16:59:47 +000012#include "llvm/Analysis/Expressions.h"
13#include "llvm/iOther.h"
Chris Lattner7991c282001-12-14 16:38:59 +000014#include <algorithm>
Chris Lattner59cd9f12001-11-04 23:24:06 +000015
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//
20const TargetData TD("LevelRaise: Should be GCC though!");
21
Chris Lattner59cd9f12001-11-04 23:24:06 +000022// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
23// with a value, then remove and delete the original instruction.
24//
25void 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//
47void 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...
Chris Lattnerc4db7542002-03-11 22:21:04 +000053 BI = BIL.insert(BI, I)+1; // Increment BI to point to instruction to delete
Chris Lattner59cd9f12001-11-04 23:24:06 +000054
55 // Replace all uses of the old instruction, and delete it.
56 ReplaceInstWithValue(BIL, BI, I);
57
Chris Lattnerc4db7542002-03-11 22:21:04 +000058 // Move BI back to point to the newly inserted instruction
Chris Lattner59cd9f12001-11-04 23:24:06 +000059 --BI;
60}
61
Chris Lattner7991c282001-12-14 16:38:59 +000062void 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
Chris Lattner8e865422002-03-21 06:24:00 +000070// InsertInstBeforeInst - Insert 'NewInst' into the basic block that 'Existing'
71// is already in, and put it right before 'Existing'. This instruction should
72// only be used when there is no iterator to Existing already around. The
73// returned iterator points to the new instruction.
74//
75BasicBlock::iterator InsertInstBeforeInst(Instruction *NewInst,
76 Instruction *Existing) {
77 BasicBlock *BB = Existing->getParent();
78 BasicBlock::InstListType &BIL = BB->getInstList();
79 BasicBlock::iterator BI = find(BIL.begin(), BIL.end(), Existing);
80 assert(BI != BIL.end() && "Inst not in it's parents BB!");
81 return BIL.insert(BI, NewInst);
82}
83
Chris Lattner7991c282001-12-14 16:38:59 +000084
Chris Lattner59cd9f12001-11-04 23:24:06 +000085
Chris Lattnerc0b90e72001-11-08 20:19:56 +000086// getStructOffsetType - Return a vector of offsets that are to be used to index
87// into the specified struct type to get as close as possible to index as we
88// can. Note that it is possible that we cannot get exactly to Offset, in which
89// case we update offset to be the offset we actually obtained. The resultant
90// leaf type is returned.
91//
92// If StopEarly is set to true (the default), the first object with the
93// specified type is returned, even if it is a struct type itself. In this
94// case, this routine will not drill down to the leaf type. Set StopEarly to
95// false if you want a leaf
96//
97const Type *getStructOffsetType(const Type *Ty, unsigned &Offset,
Chris Lattner697954c2002-01-20 22:54:45 +000098 std::vector<Value*> &Offsets,
Chris Lattnerc0b90e72001-11-08 20:19:56 +000099 bool StopEarly = true) {
Chris Lattner7991c282001-12-14 16:38:59 +0000100 if (Offset == 0 && StopEarly && !Offsets.empty())
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000101 return Ty; // Return the leaf type
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000102
Chris Lattner89a1c802001-11-26 16:59:47 +0000103 unsigned ThisOffset;
104 const Type *NextType;
105 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner7991c282001-12-14 16:38:59 +0000106 assert(Offset < TD.getTypeSize(STy) && "Offset not in composite!");
Chris Lattner89a1c802001-11-26 16:59:47 +0000107 const StructLayout *SL = TD.getStructLayout(STy);
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000108
Chris Lattner89a1c802001-11-26 16:59:47 +0000109 // This loop terminates always on a 0 <= i < MemberOffsets.size()
110 unsigned i;
111 for (i = 0; i < SL->MemberOffsets.size()-1; ++i)
112 if (Offset >= SL->MemberOffsets[i] && Offset < SL->MemberOffsets[i+1])
113 break;
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000114
Chris Lattner89a1c802001-11-26 16:59:47 +0000115 assert(Offset >= SL->MemberOffsets[i] &&
116 (i == SL->MemberOffsets.size()-1 || Offset <SL->MemberOffsets[i+1]));
117
118 // Make sure to save the current index...
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000119 Offsets.push_back(ConstantUInt::get(Type::UByteTy, i));
Chris Lattner89a1c802001-11-26 16:59:47 +0000120 ThisOffset = SL->MemberOffsets[i];
121 NextType = STy->getElementTypes()[i];
Chris Lattner7991c282001-12-14 16:38:59 +0000122 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
123 assert(Offset < TD.getTypeSize(ATy) && "Offset not in composite!");
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000124
Chris Lattner89a1c802001-11-26 16:59:47 +0000125 NextType = ATy->getElementType();
126 unsigned ChildSize = TD.getTypeSize(NextType);
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000127 Offsets.push_back(ConstantUInt::get(Type::UIntTy, Offset/ChildSize));
Chris Lattner89a1c802001-11-26 16:59:47 +0000128 ThisOffset = (Offset/ChildSize)*ChildSize;
Chris Lattner7991c282001-12-14 16:38:59 +0000129 } else {
130 Offset = 0; // Return the offset that we were able to acheive
131 return Ty; // Return the leaf type
Chris Lattner89a1c802001-11-26 16:59:47 +0000132 }
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000133
Chris Lattner89a1c802001-11-26 16:59:47 +0000134 unsigned SubOffs = Offset - ThisOffset;
Chris Lattner4736d062002-03-07 21:18:00 +0000135 const Type *LeafTy = getStructOffsetType(NextType, SubOffs,
136 Offsets, StopEarly);
Chris Lattner89a1c802001-11-26 16:59:47 +0000137 Offset = ThisOffset + SubOffs;
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000138 return LeafTy;
139}
Chris Lattner89a1c802001-11-26 16:59:47 +0000140
141// ConvertableToGEP - This function returns true if the specified value V is
142// a valid index into a pointer of type Ty. If it is valid, Idx is filled in
143// with the values that would be appropriate to make this a getelementptr
144// instruction. The type returned is the root type that the GEP would point to
145//
146const Type *ConvertableToGEP(const Type *Ty, Value *OffsetVal,
Chris Lattner697954c2002-01-20 22:54:45 +0000147 std::vector<Value*> &Indices,
Chris Lattner89a1c802001-11-26 16:59:47 +0000148 BasicBlock::iterator *BI = 0) {
Chris Lattner7991c282001-12-14 16:38:59 +0000149 const CompositeType *CompTy = dyn_cast<CompositeType>(Ty);
Chris Lattner89a1c802001-11-26 16:59:47 +0000150 if (CompTy == 0) return 0;
151
152 // See if the cast is of an integer expression that is either a constant,
153 // or a value scaled by some amount with a possible offset.
154 //
155 analysis::ExprType Expr = analysis::ClassifyExpression(OffsetVal);
156
Chris Lattner89a1c802001-11-26 16:59:47 +0000157 // Get the offset and scale now...
Chris Lattner99fb91c2002-03-21 03:04:38 +0000158 // A scale of zero with Expr.Var != 0 means a scale of 1.
159 //
160 // TODO: Handle negative offsets for C code like this:
161 // for (unsigned i = 12; i < 14; ++i) x[j*i-12] = ...
162 unsigned Offset = 0;
163 int Scale = 0;
Chris Lattner89a1c802001-11-26 16:59:47 +0000164
165 // Get the offset value if it exists...
166 if (Expr.Offset) {
167 int Val = getConstantValue(Expr.Offset);
168 if (Val < 0) return false; // Don't mess with negative offsets
169 Offset = (unsigned)Val;
170 }
171
172 // Get the scale value if it exists...
Chris Lattner99fb91c2002-03-21 03:04:38 +0000173 if (Expr.Scale) Scale = getConstantValue(Expr.Scale);
174 if (Expr.Var && Scale == 0) Scale = 1; // Scale != 0 if Expr.Var != 0
175
Chris Lattner89a1c802001-11-26 16:59:47 +0000176 // Loop over the Scale and Offset values, filling in the Indices vector for
177 // our final getelementptr instruction.
178 //
179 const Type *NextTy = CompTy;
180 do {
181 if (!isa<CompositeType>(NextTy))
182 return 0; // Type must not be ready for processing...
183 CompTy = cast<CompositeType>(NextTy);
184
185 if (const StructType *StructTy = dyn_cast<StructType>(CompTy)) {
Chris Lattner89a1c802001-11-26 16:59:47 +0000186 unsigned ActualOffset = Offset;
187 NextTy = getStructOffsetType(StructTy, ActualOffset, Indices);
Chris Lattner99fb91c2002-03-21 03:04:38 +0000188 if (StructTy == NextTy && ActualOffset == 0)
189 return 0; // No progress. :(
Chris Lattner89a1c802001-11-26 16:59:47 +0000190 Offset -= ActualOffset;
191 } else {
Chris Lattner7991c282001-12-14 16:38:59 +0000192 const Type *ElTy = cast<SequentialType>(CompTy)->getElementType();
Chris Lattner99fb91c2002-03-21 03:04:38 +0000193 if (!ElTy->isSized())
194 return 0; // Type is unreasonable... escape!
Chris Lattner89a1c802001-11-26 16:59:47 +0000195 unsigned ElSize = TD.getTypeSize(ElTy);
Chris Lattner99fb91c2002-03-21 03:04:38 +0000196 int ElSizeS = (int)ElSize;
Chris Lattner89a1c802001-11-26 16:59:47 +0000197
198 // See if the user is indexing into a different cell of this array...
Chris Lattner99fb91c2002-03-21 03:04:38 +0000199 if (Scale && (Scale >= ElSizeS || -Scale >= ElSizeS)) {
Chris Lattner2dc48bd2001-12-05 19:41:16 +0000200 // A scale n*ElSize might occur if we are not stepping through
201 // array by one. In this case, we will have to insert math to munge
202 // the index.
203 //
Chris Lattner99fb91c2002-03-21 03:04:38 +0000204 int ScaleAmt = Scale/ElSizeS;
205 if (Scale-ScaleAmt*ElSizeS)
Chris Lattner2dc48bd2001-12-05 19:41:16 +0000206 return 0; // Didn't scale by a multiple of element size, bail out
Chris Lattner7991c282001-12-14 16:38:59 +0000207 Scale = 0; // Scale is consumed
Chris Lattner2dc48bd2001-12-05 19:41:16 +0000208
209 unsigned Index = Offset/ElSize; // is zero unless Offset > ElSize
210 Offset -= Index*ElSize; // Consume part of the offset
211
212 if (BI) { // Generate code?
213 BasicBlock *BB = (**BI)->getParent();
214 if (Expr.Var->getType() != Type::UIntTy) {
215 CastInst *IdxCast = new CastInst(Expr.Var, Type::UIntTy);
216 if (Expr.Var->hasName())
217 IdxCast->setName(Expr.Var->getName()+"-idxcast");
218 *BI = BB->getInstList().insert(*BI, IdxCast)+1;
219 Expr.Var = IdxCast;
220 }
221
Chris Lattner7c3f4152001-12-07 04:26:02 +0000222 if (ScaleAmt && ScaleAmt != 1) {
223 // If we have to scale up our index, do so now
Chris Lattner99fb91c2002-03-21 03:04:38 +0000224 Value *ScaleAmtVal = ConstantUInt::get(Type::UIntTy,
225 (unsigned)ScaleAmt);
Chris Lattner2dc48bd2001-12-05 19:41:16 +0000226 Instruction *Scaler = BinaryOperator::create(Instruction::Mul,
Chris Lattner99fb91c2002-03-21 03:04:38 +0000227 Expr.Var, ScaleAmtVal);
Chris Lattner2dc48bd2001-12-05 19:41:16 +0000228 if (Expr.Var->hasName())
229 Scaler->setName(Expr.Var->getName()+"-scale");
230
231 *BI = BB->getInstList().insert(*BI, Scaler)+1;
232 Expr.Var = Scaler;
233 }
234
235 if (Index) { // Add an offset to the index
236 Value *IndexAmt = ConstantUInt::get(Type::UIntTy, Index);
237 Instruction *Offseter = BinaryOperator::create(Instruction::Add,
238 Expr.Var, IndexAmt);
239 if (Expr.Var->hasName())
240 Offseter->setName(Expr.Var->getName()+"-offset");
241 *BI = BB->getInstList().insert(*BI, Offseter)+1;
242 Expr.Var = Offseter;
243 }
244 }
245
246 Indices.push_back(Expr.Var);
Chris Lattner99fb91c2002-03-21 03:04:38 +0000247 Expr.Var = 0;
Chris Lattner2dc48bd2001-12-05 19:41:16 +0000248 } else if (Offset >= ElSize) {
Chris Lattner89a1c802001-11-26 16:59:47 +0000249 // Calculate the index that we are entering into the array cell with
250 unsigned Index = Offset/ElSize;
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000251 Indices.push_back(ConstantUInt::get(Type::UIntTy, Index));
Chris Lattner89a1c802001-11-26 16:59:47 +0000252 Offset -= Index*ElSize; // Consume part of the offset
253
Chris Lattner754cf412002-03-14 16:37:04 +0000254 } else if (isa<ArrayType>(CompTy) || Indices.empty()) {
Chris Lattner89a1c802001-11-26 16:59:47 +0000255 // Must be indexing a small amount into the first cell of the array
256 // Just index into element zero of the array here.
257 //
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000258 Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
Chris Lattner7991c282001-12-14 16:38:59 +0000259 } else {
260 return 0; // Hrm. wierd, can't handle this case. Bail
Chris Lattner89a1c802001-11-26 16:59:47 +0000261 }
262 NextTy = ElTy;
263 }
264 } while (Offset || Scale); // Go until we're done!
265
266 return NextTy;
267}